Levenshtein distance: Difference between revisions

Add bruijn
(→‎{{header|Picat}}: Split into subsections. Added {{out}})
(Add bruijn)
 
(35 intermediate revisions by 18 users not shown)
Line 31:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F minimumEditDistance(=s1, =s2)
I s1.len > s2.len
(s1, s2) = (s2, s1)
Line 48:
 
print(minimumEditDistance(‘kitten’, ‘sitting’))
print(minimumEditDistance(‘rosettacode’, ‘raisethysword’))</langsyntaxhighlight>
 
{{out}}
Line 57:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Levenshtein distance - 22/04/2020
LEVENS CSECT
USING LEVENS,R13 base register
Line 229:
XDEC DS CL12 temp fo xdeco
REGEQU
END LEVENS</langsyntaxhighlight>
{{out}}
<pre>
Line 240:
 
=={{header|Action!}}==
{{Improve||The output shown does not appear to match the PrintF calls in the code}}
<lang action>
<syntaxhighlight lang="action">
DEFINE STRING="CHAR ARRAY" ; sys.act
DEFINE width="15" ; max characters 14
Line 319 ⟶ 320:
;PrintF("Damerau Levenshtein Distance=%U%E%E",result)
RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>kitten, sitting: 3
Line 326 ⟶ 327:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Main is
Line 359 ⟶ 360:
("rosettacode -> raisethysword:" &
Integer'Image (Levenshtein_Distance ("rosettacode", "raisethysword")));
end Main;</langsyntaxhighlight>
{{out}}
<pre>kitten -> sitting: 3
Line 366 ⟶ 367:
=={{header|Aime}}==
{{trans|C}}
<langsyntaxhighlight lang="aime">integer
dist(data s, t, integer i, j, list d)
{
Line 410 ⟶ 411:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre>`rosettacode' to `raisethysword' is 8
Line 417 ⟶ 418:
=={{header|ALGOL 68}}==
{{Trans|Action!}}
...largely to highlight the syntactic similarities.
<lang algol68># Calculate Levenshtein distance between strings - translated from the Action! sample #
<br>
Non-recursive algorithm - although Algol 68 supports recursion, Action! doesn't.
<syntaxhighlight lang="algol68"># Calculate Levenshtein distance between strings - translated from the Action! sample #
BEGIN
 
PROC damerau PROC levenshtein distance = (STRING str1, str2)INT:
BEGIN
 
INT m=UPB str1;
INT n=UPB str2;
 
(0:m,0:n)INT matrix;
FOR i FROM 0 TO m DO FOR j FROM 0 TO n DO matrix(i,j):=0 OD OD;
FOR i TO m DO matrix(i,1):=i OD;
FOR j TO n DO matrix(1,j):=j OD;
FOR j FROM 1 TO n DO
FOR i FROM 1 TO m DO
IF str1(i) = str2(j) THEN
matrix(i,j):=matrix(i-1, j-1) # no operation required #
ELSE
INT min := matrix(i-1,j)+1 ; # REMdeletion delete #
INT k = matrix(i,j-1)+1 ; # REMinsertion insert #
INT l = matrix(i-1, j-1)+1 ; # REM substitution #
IF k < min THEN min:=k FI;
IF l < min THEN min:=l FI;
matrix(i,j):=min
COMMENT
;
# transposition for Damerau Levenshtein Distance #
IF i>1 AND j>1 THEN
IF str1(i) = str2(j-1) AND str1(i-1) = str2(j) THEN
INT min:=matrix(i,j);
INT tmp=matrix(i-2,j-2)+1;
IF min>tmp THEN min=tmp FI;
matrix(i,j):=min # REM transposition #
FI
FI
OD
COMMENT
FIOD;
ODmatrix(m,n)
ODEND;
matrix(m,n)
END;
 
STRING word 1, word 2;
word 1 :="kitten"; word 2 := "sitting";
print((word 1," -> ",word 2,newline": "));
print(("Levenshtein Distance=: ",whole(damerau levenshtein distance(word 1,word 2),0),newline));
word 1 := "rosettacode"; word 2 := "raisethysword";
print((word 1," -> ",word 2,newline": "));
print(("Levenshtein Distance=: ",whole(damerau levenshtein distance(word 1,word 2),0),newline));
word 1 := "qwerty"; word 2 := "qweryt";
print((word 1," -> ",word 2,newline": "));
print(("Levenshtein Distance=: ",whole(damerau levenshtein distance(word 1,word 2),0),newline));
 
END</lang>
word 1 := "Action!"; word 2 := "Algol 68";
print((word 1," -> ",word 2,": "));
print(("Levenshtein Distance: ",whole(levenshtein distance(word 1,word 2),0),newline))
END</syntaxhighlight>
{{out}}
<pre>
kitten -> sitting: Levenshtein Distance: 3
rosettacode -> raisethysword: Levenshtein Distance=3: 8
qwerty -> qweryt: Levenshtein Distance: 2
rosettacode - raisethysword
Action! -> Algol 68: Levenshtein Distance=8: 7
qwerty - qweryt
Levenshtein Distance=2
</pre>
 
Line 488 ⟶ 482:
===Iteration===
Translation of the "fast" C-version
<langsyntaxhighlight AppleScriptlang="applescript">set dist to findLevenshteinDistance for "sunday" against "saturday"
to findLevenshteinDistance for s1 against s2
script o
Line 542 ⟶ 536:
end if
end if
end min3</langsyntaxhighlight>
 
===Composition of generic functions===
Line 549 ⟶ 543:
 
In the ancient tradition of "''Use library functions whenever feasible.''" (for better productivity), and also in the even older functional tradition of composing values (for better reliability) rather than sequencing actions:
<langsyntaxhighlight AppleScriptlang="applescript">-- levenshtein :: String -> String -> Int
on levenshtein(sa, sb)
set {s1, s2} to {characters of sa, characters of sb}
Line 702 ⟶ 696:
map(result, items 1 thru ¬
minimum({length of xs, length of ys, length of zs}) of xs)
end zip3</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{3, 3, 8, 8}</langsyntaxhighlight>
 
=={{header|Arc}}==
Line 710 ⟶ 704:
O(n * m) time, linear space, using lists instead of vectors
 
<langsyntaxhighlight lang="lisp">(def levenshtein (str1 str2)
(withs l1 len.str1
l2 len.str2
Line 725 ⟶ 719:
next))
(= row nrev.next)))
row.l1))</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">print levenshtein "kitten" "sitting"</langsyntaxhighlight>
 
{{out}}
Line 737 ⟶ 731:
=={{header|AutoHotkey}}==
{{trans|Go}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">levenshtein(s, t){
If s =
return StrLen(t)
Line 755 ⟶ 749:
s1 := "kitten"
s2 := "sitting"
MsgBox % "distance between " s1 " and " s2 ": " levenshtein(s1, s2)</langsyntaxhighlight>It correctly outputs '3'
 
=={{header|AWK}}==
Line 761 ⟶ 755:
Slavishly copied from the very clear AutoHotKey example.
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 806 ⟶ 800:
}
 
</syntaxhighlight>
</lang>
 
Example output:
Line 816 ⟶ 810:
Alternative, much faster but also less readable lazy-evaluation version from http://awk.freeshell.org/LevenshteinEditDistance
(where the above takes e.g. 0m44.904s in gawk 4.1.3 for 5 edits (length 10 and 14 strings), this takes user 0m0.004s):
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
function levdist(str1, str2, l1, l2, tog, arr, i, j, a, b, c) {
Line 844 ⟶ 838:
return arr[tog, j-1]
}
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> PRINT "'kitten' -> 'sitting' has distance " ;
PRINT ; FNlevenshtein("kitten", "sitting")
PRINT "'rosettacode' -> 'raisethysword' has distance " ;
Line 874 ⟶ 868:
NEXT
NEXT j%
= d%(i%-1,j%-1)</langsyntaxhighlight>
'''Output:'''
<pre>
Line 883 ⟶ 877:
=={{header|BQN}}==
Recursive slow version:
<langsyntaxhighlight BQNlang="bqn">Levenshtein ← {
𝕨 𝕊"": ≠𝕨;
""𝕊 𝕩: ≠𝕩;
Line 889 ⟶ 883:
Tail←1⊸↓
𝕨 =○⊑◶⟨1+·⌊´ 𝕊○Tail ∾ Tail⊸𝕊 ∾ 𝕊⟜Tail, 𝕊○Tail⟩ 𝕩
}</langsyntaxhighlight>
Fast version:
<langsyntaxhighlight BQNlang="bqn">Levenshtein ← @⊸∾⊸{¯1⊑(↕≠𝕨)𝕨{(1⊸+⊸⌊`1⊸+⌊⊑⊸»+𝕨≠𝕗˙)𝕩}´⌽𝕩}</langsyntaxhighlight>
{{out|Example use}}
<syntaxhighlight lang="text"> "kitten" Levenshtein "sitting"
3
"Saturday" Levenshtein "Sunday"
3
"rosettacode" Levenshtein "raisethysword"
8</langsyntaxhighlight>
 
=={{header|Bracmat}}==
{{trans|C}}
Recursive method, but with memoization.
<langsyntaxhighlight lang="bracmat">(levenshtein=
lev cache
. ( lev
Line 927 ⟶ 921:
)
& new$hash:?cache
& lev$!arg);</langsyntaxhighlight>
{{out|Demonstrating}}
<pre> levenshtein$(kitten,sitting)
Line 933 ⟶ 927:
levenshtein$(rosettacode,raisethysword)
8</pre>
 
=={{header|Bruijn}}==
{{trans|Haskell}}
Recursive and non-memoized method:
 
<syntaxhighlight lang="bruijn>
:import std/Combinator .
:import std/Char C
:import std/List .
:import std/Math .
 
levenshtein y [[[∅?1 ∀0 (∅?0 ∀1 (0 (1 [[[[go]]]])))]]]
go (C.eq? 3 1) (6 2 0) ++(lmin ((6 2 0) : ((6 5 0) : {}(6 2 4))))
 
:test ((levenshtein "rosettacode" "raisethysword") =? (+8)) ([[1]])
:test ((levenshtein "kitten" "sitting") =? (+3)) ([[1]])
</syntaxhighlight>
 
=={{header|C}}==
Recursive method. Deliberately left in an inefficient state to show the recursive nature of the algorithm; notice how it would have become the Wikipedia algorithm if we memoized the function against parameters <code>ls</code> and <code>lt</code>.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <string.h>
 
Line 980 ⟶ 991:
 
return 0;
}</langsyntaxhighlight>
Take the above and add caching, we get (in [[C99]]):
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 1,025 ⟶ 1,036:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
This is a straightforward translation of the Wikipedia pseudocode.
<langsyntaxhighlight lang="csharp">using System;
 
namespace LevenshteinDistance
Line 1,078 ⟶ 1,089:
}
}
}</langsyntaxhighlight>
{{out|Example output}}
<pre>
Line 1,089 ⟶ 1,100:
 
=={{header|C++}}==
<langsyntaxhighlight lang="c">#include <string>
#include <iostream>
using namespace std;
Line 1,143 ⟶ 1,154:
 
return 0;
}</langsyntaxhighlight>
{{out|Example output}}
<pre>
Line 1,151 ⟶ 1,162:
 
===Generic ISO C++ version===
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <numeric>
Line 1,190 ⟶ 1,201:
<< levenshtein_distance(s0, s1) << std::endl;
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,200 ⟶ 1,211:
 
===Recursive Version===
<langsyntaxhighlight lang="lisp">(defn levenshtein [str1 str2]
(let [len1 (count str1)
len2 (count str2)]
Line 1,212 ⟶ 1,223:
(levenshtein (rest str1) (rest str2))))))))
 
(println (levenshtein "rosettacode" "raisethysword"))</langsyntaxhighlight>
{{out}}
<pre>8</pre>
 
===Iterative version===
<langsyntaxhighlight lang="lisp">(defn levenshtein [w1 w2]
(letfn [(cell-value [same-char? prev-row cur-row col-idx]
(min (inc (nth prev-row col-idx))
Line 1,237 ⟶ 1,248:
i))))
[row-idx] (range 1 (count prev-row)))]
(recur (inc row-idx) max-rows next-prev-row))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">min = proc [T: type] (a, b: T) returns (T)
where T has lt: proctype (T,T) returns (bool)
if a<b
Line 1,283 ⟶ 1,294:
show("kitten", "sitting")
show("rosettacode", "raisethysword")
end start_up</langsyntaxhighlight>
{{out}}
<pre>kitten => sitting: 3
Line 1,290 ⟶ 1,301:
=={{header|COBOL}}==
GnuCobol 2.2
<langsyntaxhighlight lang="cobol">
identification division.
program-id. Levenshtein.
Line 1,353 ⟶ 1,364:
display trim(string-a) " -> " trim(string-b) " = " trim(distance)
.
</syntaxhighlight>
</lang>
{{out|Output}}
<pre>
Line 1,362 ⟶ 1,373:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">levenshtein = (str1, str2) ->
# more of less ported simple algorithm from JS
m = str1.length
Line 1,391 ⟶ 1,402:
console.log levenshtein("stop", "tops")
console.log levenshtein("yo", "")
console.log levenshtein("", "yo")</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun levenshtein (a b)
(let* ((la (length a))
(lb (length b))
Line 1,404 ⟶ 1,415:
((aref rec x y) (aref rec x y))
(t (setf (aref rec x y)
(min (+ (if (char= (char aleven (1- la x)) (char b (- lb y))) 0 1)
(min+ (leven x (1- xy)) y1)
(+ (leven (1- x) (1- y)) (if (char= (levenchar a (- la x)) (char b (1- lb y))) 0 1))))))))
(leven (1- x) (1- y)))))))))
(leven la lb))))
 
(print (levenshtein "rosettacode" "raisethysword"))</langsyntaxhighlight>
{{out}}
<pre>8</pre>
Line 1,416 ⟶ 1,426:
=={{header|Crystal}}==
The standard library includes [https://crystal-lang.org/api/0.19.2/Levenshtein.html levenshtein] module
<langsyntaxhighlight lang="ruby">require "levenshtein"
puts Levenshtein.distance("kitten", "sitting")
puts Levenshtein.distance("rosettacode", "raisethysword")
</syntaxhighlight>
</lang>
{{out}}
<pre>3
Line 1,425 ⟶ 1,435:
 
{{trans|Ruby 1st version}}
<langsyntaxhighlight lang="ruby">module Levenshtein
def self.distance(a, b)
Line 1,448 ⟶ 1,458:
Levenshtein.test
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,457 ⟶ 1,467:
 
{{trans|Ruby 2nd version}}
<langsyntaxhighlight lang="ruby">def levenshtein_distance(str1, str2)
n, m = str1.size, str2.size
max = n / 2
Line 1,488 ⟶ 1,498:
puts "distance(#{a}, #{b}) = #{levenshtein_distance(a, b)}"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,499 ⟶ 1,509:
===Standard Version===
The standard library [http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html#levenshteinDistance std.algorithm] module includes a Levenshtein distance function:
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm;
 
levenshteinDistance("kitten", "sitting").writeln;
}</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Line 1,509 ⟶ 1,519:
===Iterative Version===
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
int distance(in string s1, in string s2) pure nothrow {
Line 1,540 ⟶ 1,550:
foreach (p; [["kitten", "sitting"], ["rosettacode", "raisethysword"]])
writefln("distance(%s, %s): %d", p[0], p[1], distance(p[0], p[1]));
}</langsyntaxhighlight>
 
===Memoized Recursive Version===
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.algorithm, std.functional;
 
uint lDist(T)(in const(T)[] s, in const(T)[] t) nothrow {
Line 1,558 ⟶ 1,568:
lDist("kitten", "sitting").writeln;
lDist("rosettacode", "raisethysword").writeln;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Levenshtein_distanceTest;
 
Line 1,626 ⟶ 1,636:
readln;
end.
</syntaxhighlight>
</lang>
 
 
Line 1,632 ⟶ 1,642:
=={{header|DWScript}}==
Based on Wikipedia version
<langsyntaxhighlight lang="delphi">function LevenshteinDistance(s, t : String) : Integer;
var
i, j : Integer;
Line 1,654 ⟶ 1,664:
end;
 
PrintLn(LevenshteinDistance('kitten', 'sitting'));</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func levenshtein(s, t) {
var n = s.Length()
var m = t.Length()
Line 1,701 ⟶ 1,711:
}
run("rosettacode", "raisethysword")</langsyntaxhighlight>
 
{{out}}
 
<pre>rosettacode -> raisethysword = 8</pre>
 
=={{header|EasyLang}}==
{{trans|AWK}}
 
<syntaxhighlight lang=easylang>
func dist s1$ s2$ .
if len s1$ = 0
return len s2$
.
if len s2$ = 0
return len s1$
.
c1$ = substr s1$ 1 1
c2$ = substr s2$ 1 1
s1rest$ = substr s1$ 2 len s1$
s2rest$ = substr s2$ 2 len s2$
#
if c1$ = c2$
return dist s1rest$ s2rest$
.
min = lower dist s1rest$ s2rest$ dist s1$ s2rest$
min = lower min dist s1rest$ s2rest$
return min + 1
.
print dist "kitten" "sitting"
print dist "rosettacode" "raisethysword"
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; Recursive version adapted from Clojure
;; Added necessary memoization
Line 1,737 ⟶ 1,774:
 
(levenshtein "rosettacode" "raisethysword") → 8
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
This code is translated from Haskell version.
 
<langsyntaxhighlight lang="ela">open list
 
levenshtein s1 s2 = last <| foldl transform [0 .. length s1] s2
where transform (n::ns')@ns c = scanl calc (n+1) <| zip3 s1 ns ns'
where calc z (c', x, y) = minimum [y+1, z+1, x + toInt (c' <> c)]</langsyntaxhighlight>
 
Executing:
 
<langsyntaxhighlight lang="ela">(levenshtein "kitten" "sitting", levenshtein "rosettacode" "raisethysword")</langsyntaxhighlight>
{{out}}
<pre>(3, 8)</pre>
Line 1,756 ⟶ 1,793:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Levenshtein do
def distance(a, b) do
ta = String.downcase(a) |> to_charlist |> List.to_tuple
Line 1,783 ⟶ 1,820:
Enum.each(Enum.chunk(words, 2), fn [a,b] ->
IO.puts "distance(#{a}, #{b}) = #{Levenshtein.distance(a,b)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,794 ⟶ 1,831:
=={{header|Erlang}}==
Here are two implementations. The first is the naive version, the second is a memoized version using Erlang's dictionary datatype.
<langsyntaxhighlight lang="erlang">
-module(levenshtein).
-compile(export_all).
Line 1,830 ⟶ 1,867:
{L,dict:store({S,T},L,C3)}
end.
</syntaxhighlight>
</lang>
Below is a comparison of the runtimes, measured in microseconds, between the two implementations.
<langsyntaxhighlight lang="erlang">
68> timer:tc(levenshtein,distance,["rosettacode","raisethysword"]).
{774799,8} % {Time, Result}
Line 1,841 ⟶ 1,878:
71> timer:tc(levenshtein,distance_cached,["kitten","sitting"]).
{213,3}
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM LEVENSHTEIN
 
Line 1,888 ⟶ 1,925:
!$ERASE D%
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}<pre>
'kitten' -> 'sitting' has distance 3
Line 1,896 ⟶ 1,933:
=={{header|Euphoria}}==
Code by Jeremy Cowgar from the [http://www.rapideuphoria.com/cgi-bin/asearch.exu?gen=on&keywords=Levenshtein Euphoria File Archive].
<langsyntaxhighlight lang="euphoria">function min(sequence s)
atom m
m = s[1]
Line 1,942 ⟶ 1,979:
 
? levenshtein("kitten", "sitting")
? levenshtein("rosettacode", "raisethysword")</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,950 ⟶ 1,987:
=={{header|F_Sharp|F#}}==
=== Standard version ===
<syntaxhighlight lang="fsharp">
<lang FSharp>
open System
 
Line 1,983 ⟶ 2,020:
 
Console.ReadKey () |> ignore
</syntaxhighlight>
</lang>
 
=== Recursive Version ===
<syntaxhighlight lang="fsharp">
<lang FSharp>
open System
 
 
let levenshtein (s1:string) (s2:string) : int =
 
let s1' = s1.ToCharArray()
let s2' = s2.ToCharArray()
 
let rec dist l1 l2 =
match (l1,l2) with
| (l1, 0) -> l1
| (0, l2) -> l2
| (l1, l2) ->
if s1'.[l1-1] = s2'.[l2-1] then dist (l1-1) (l2-1)
else
let d1 = dist (l1 - 1) l2
let d2 = dist l1 (l2 - 1)
let d3 = dist (l1 - 1) (l2 - 1)
1 + Math.Min(d1,(Math.Min(d2,d3)))
 
dist s1.Length s2.Length
let rec dist l1 l2 = match (l1,l2) with
| (l1, 0) -> l1
| (0, l2) -> l2
| (l1, l2) ->
if s1'.[l1-1] = s2'.[l2-1] then dist (l1-1) (l2-1)
else
let d1 = dist (l1 - 1) l2
let d2 = dist l1 (l2 - 1)
let d3 = dist (l1 - 1) (l2 - 1)
1 + Math.Min(d1,(Math.Min(d2,d3)))
dist s1.Length s2.Length
 
printfn "dist(kitten, sitting) = %i" (levenshtein "kitten" "sitting")
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: lcs prettyprint ;
"kitten" "sitting" levenshtein .</langsyntaxhighlight>
{{out}}
<pre>
Line 2,021 ⟶ 2,058:
=={{header|Forth}}==
{{trans|C}}
<langsyntaxhighlight lang="forth">: levenshtein ( a1 n1 a2 n2 -- n3)
dup \ if either string is empty, difference
if \ is inserting all chars from the other
Line 2,043 ⟶ 2,080:
 
s" kitten" s" sitting" levenshtein . cr
s" rosettacode" s" raisethysword" levenshtein . cr</langsyntaxhighlight>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
program demo_edit_distance
character(len=:),allocatable :: sources(:),targets(:)
Line 2,085 ⟶ 2,122:
 
end program demo_edit_distance
</syntaxhighlight>
</lang>
{{out}}<pre>
<pre>
kitten sitting 3 T
rosettacode raisethysword 8 T
Line 2,095 ⟶ 2,133:
T
</pre>
 
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Uses the "iterative with two matrix rows" algorithm
Line 2,146 ⟶ 2,183:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,157 ⟶ 2,194:
=={{header|Frink}}==
Frink has a built-in function to calculate the Levenshtein edit distance between two strings:
<langsyntaxhighlight lang="frink">println[editDistance["kitten","sitting"]]</langsyntaxhighlight>
It also has a function to calculate the Levenshtein-Damerau edit distance, <CODE>editDistanceDamerau[<I>str1</I>,<I>str2</I>]</CODE>. This is similar to the <CODE>editDistance</CODE> function but also allows ''swaps'' between two adjoining characters, which count as an edit distance of 1. This may make distances between some strings shorter, by say, treating transposition errors in a word as a less expensive operation than in the pure Levenshtein algorithm, and is generally more useful in more circumstances.
 
=={{header|FutureBasic}}==
Recursive version.
Based on Wikipedia algorithm. Suitable for Pascal strings.
<langsyntaxhighlight lang="futurebasic">
local fn LevenshteinDistance( s1 as CFStringRef, s2 as CFStringRef ) as NSInteger
include "ConsoleWindow"
NSInteger result
// If strings are equal, Levenshtein distance is 0
if ( fn StringIsEqual( s1, s2 ) ) then result = 0 : exit fn
// If either string is empty, then distance is the length of the other string.
if ( len(s1) == 0) then result = len(s2) : exit fn
if ( len(s2) == 0) then result = len(s1) : exit fn
// The remaining recursive process uses first characters and remainder of each string.
CFStringRef s1First = fn StringSubstringToIndex( s1, 1 )
CFStringRef s2First = fn StringSubstringToIndex( s2, 1 )
CFStringRef s1Rest = mid( s1, 1, len(s1) -1 )
CFStringRef s2Rest = mid( s2, 1, len(s2) -1 )
// If leading characters are the same, then distance is that between the rest of the strings.
if fn StringIsEqual( s1First, s2First ) then result = fn LevenshteinDistance( s1Rest, s2Rest ) : exit fn
// Find the distances between sub strings.
NSInteger distA = fn LevenshteinDistance( s1Rest, s2 )
NSInteger distB = fn LevenshteinDistance( s1, s2Rest )
NSInteger distC = fn LevenshteinDistance( s1Rest, s2Rest )
// Return the minimum distance between substrings.
NSInteger minDist = distA
if ( distB < minDist ) then minDist = distB
if ( distC < minDist ) then minDist = distC
result = minDist + 1 // Include change for the first character.
end fn = result
 
local fn LevenshteinDistance( aStr as Str255, bStr as Str255 ) as long
dim as long m, n, i, j, min, k, l
dim as long distance( 255, 255 )
 
m = len(aStr)
n = len(bStr)
for i = 0 to m
distance( i, 0 ) = i
next
 
for j = 0 to n
distance( 0, j ) = j
next
for j = 1 to n
for i = 1 to m
if mid$( aStr, i, 1 ) == mid$( bStr, j, 1 )
distance( i, j ) = distance( i-1, j-1 )
else
min = distance( i-1, j ) + 1
k = distance( i, j - 1 ) + 1
l = distance( i-1, j-1 ) + 1
if k < min then min = k
if l < min then min = l
distance( i, j ) = min
end if
next
next
end fn = distance( m, n )
 
NSInteger i
dim as long i
dim as Str255CFStringRef testStr( 56, 2 )
 
testStr( 0, 0 ) = @"kitten" : testStr( 0, 1 ) = @"sitting"
testStr( 1, 0 ) = @"rosettacode" : testStr( 1, 1 ) = @"raisethysword"
testStr( 2, 0 ) = @"Saturday" : testStr( 2, 1 ) = @"Sunday"
testStr( 3, 0 ) = @"FutureBasic" : testStr( 3, 1 ) = @"FutureBasic"
testStr( 4, 0 ) = @"rave"here's a bunch of words : testStr( 4, 1 ) = @"ravel"
testStr( 45, 10 ) = @"black"to wring out this code : testStr( 5, 1 ) = @"slack"
testStr( 6, 0 ) = @"rave" : testStr( 6, 1 ) = @"grave"
 
for i = 0 to 46
print @"1st string = "; testStr( i, 0 )
print @"2nd string = "; testStr( i, 1 )
print @"Levenshtein distance = "; fn LevenshteinDistance( testStr( i, 0 ), testStr( i, 1 ) )
print
next
</lang>
 
HandleEvents
Output:
</syntaxhighlight>
 
{{output}}
<pre>
1st string = kitten
Line 2,232 ⟶ 2,271:
Levenshtein distance = 0
 
1st string = here's a bunch of wordsrave
2nd string = to wring out this coderavel
Levenshtein distance = 181
 
1st string = black
2nd string = slack
Levenshtein distance = 1
 
1st string = rave
2nd string = grave
Levenshtein distance = 1
</pre>
 
=={{header|Go}}==
WP algorithm:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,276 ⟶ 2,323:
}
return d[len(s)][len(t)]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,282 ⟶ 2,329:
</pre>
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,305 ⟶ 2,352:
fmt.Printf("distance between %s and %s: %d\n", s1, s2,
levenshtein(s1, s2))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,312 ⟶ 2,359:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def distance(String str1, String str2) {
def dist = new int[str1.size() + 1][str2.size() + 1]
(0..str1.size()).each { dist[it][0] = it }
Line 2,330 ⟶ 2,377:
println "Checking distance(${key[0]}, ${key[1]}) == $dist"
assert distance(key[0], key[1]) == dist
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,339 ⟶ 2,386:
 
=={{header|Haskell}}==
 
<lang haskell>levenshtein :: Eq a => [a] -> [a] -> Int
===Implementation 1===
<syntaxhighlight lang="haskell">levenshtein :: Eq a => [a] -> [a] -> Int
levenshtein s1 s2 = last $ foldl transform [0 .. length s1] s2
where
Line 2,347 ⟶ 2,396:
 
main :: IO ()
main = print (levenshtein "kitten" "sitting")</langsyntaxhighlight>
{{Out}}
<pre>3</pre>
 
===Implementation 2===
<syntaxhighlight lang="haskell">levenshtein :: Eq a => [a] -> [a] -> Int
levenshtein s1 [] = length s1
levenshtein [] s2 = length s2
levenshtein s1@(s1Head:s1Tail) s2@(s2Head:s2Tail)
| s1Head == s2Head = levenshtein s1Tail s2Tail
| otherwise = 1 + minimum [score1, score2, score3]
where score1 = levenshtein s1Tail s2Tail
score2 = levenshtein s1 s2Tail
score3 = levenshtein s1Tail s2
 
main :: IO ()
main = print (levenshtein "kitten" "sitting")</syntaxhighlight>
{{Out}}
<pre>3</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="unicon">procedure main()
every process(!&input)
end
Line 2,372 ⟶ 2,437:
 
return d[n,m]-1
end</langsyntaxhighlight>
{{out|Example}}
<pre>
Line 2,383 ⟶ 2,448:
=={{header|Io}}==
A <code>levenshtein</code> method is available on strings when the standard <code>Range</code> addon is loaded.
<syntaxhighlight lang="text">Io 20110905
Io> Range ; "kitten" levenshtein("sitting")
==> 3
Io> "rosettacode" levenshtein("raisethysword")
==> 8
Io> </langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "Levensht.bas"
110 LET S1$="kitten":LET S2$="sitting"
120 PRINT "The Levenshtein distance between """;S1$;""" and """;S2$;""" is:";LEVDIST(S1$,S2$)
130 DEF LEVDIST(S$,T$)
140 LET N=LEN(T$):LET M=LEN(S$)
150 NUMERIC D(0 TO M,0 TO N)
160 FOR I=0 TO M
170 LET D(I,0)=I
180 NEXT
190 FOR J=0 TO N
200 LET D(0,J)=J
210 NEXT
220 FOR J=1 TO N
230 FOR I=1 TO M
240 IF S$(I)=T$(J) THEN
250 LET D(I,J)=D(I-1,J-1)
260 ELSE
270 LET D(I,J)=MIN(D(I-1,J)+1,MIN(D(I,J-1)+1,D(I-1,J-1)+1))
280 END IF
290 NEXT
300 NEXT
310 LET LEVDIST=D(M,N)
320 END DEF</syntaxhighlight>
 
=={{header|J}}==
One approach would be a literal transcription of the [[wp:Levenshtein_distance#Computing_Levenshtein_distance|wikipedia implementation]]:
<langsyntaxhighlight lang="j">levenshtein=:4 :0
D=. x +/&i.&>:&# y
for_i.1+i.#x do.
Line 2,405 ⟶ 2,495:
end.
{:{:D
)</langsyntaxhighlight>
 
First, we setup up an matrix of costs, with 0 or 1 for unexplored cells (1 being where the character pair corresponding to that cell position has two different characters). Note that the "cost to reach the empty string" cells go on the bottom and the right, instead of the top and the left, because this works better with J's "[http://www.jsoftware.com/help/dictionary/d420.htm insert]" operation (which we will call "reduce" in the next paragraph here. It could also be thought of as a right fold which has been constrained such the initial value is the identity value for the operation. Or, just think of it as inserting its operation between each item of its argument...).
Line 2,415 ⟶ 2,505:
We can also do the usual optimization where we only represent one row of the distance matrix at a time:
 
<langsyntaxhighlight lang="j">levdist =:4 :0
'a b'=. (x;y) /: (#x),(#y)
D=. >: iz =. i.#b
Line 2,422 ⟶ 2,512:
end.
{:D
)</langsyntaxhighlight>
{{out|Example use}}
<langsyntaxhighlight lang="j"> 'kitten' levenshtein 'sitting'
3
'kitten' levdist 'sitting'
3</langsyntaxhighlight>
Time and space use:
<syntaxhighlight lang="j">
<lang j>
timespacex '''kitten'' levenshtein ''sitting'''
0.000113 6016
timespacex '''kitten'' levdist ''sitting'''
1.5e_5 4416</langsyntaxhighlight>
So the levdist implementation is about 7 times faster for this example (which approximately corresponds to the length of the shortest string)
See the [[j:Essays/Levenshtein Distance|Levenshtein distance essay]] on the Jwiki for additional solutions.
Line 2,439 ⟶ 2,529:
=={{header|Java}}==
Based on the definition for Levenshtein distance given in the Wikipedia article:
<langsyntaxhighlight lang="java">public class Levenshtein {
 
public static int distance(String a, String b) {
Line 2,466 ⟶ 2,556:
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}</langsyntaxhighlight>
{{out}}
<pre>distance(kitten, sitting) = 3
Line 2,473 ⟶ 2,563:
</pre>
{{trans|C}}
<langsyntaxhighlight lang="java">public class Levenshtein{
public static int levenshtein(String s, String t){
/* if either string is empty, difference is inserting all chars
Line 2,518 ⟶ 2,608:
+ levenshtein(sb1.reverse().toString(), sb2.reverse().toString()));
}
}</langsyntaxhighlight>
{{out}}
<pre>distance between 'kitten' and 'sitting': 3
Line 2,526 ⟶ 2,616:
===Iterative space optimized (even bounded) ===
{{trans|Python}}
<langsyntaxhighlight lang="java">
import static java.lang.Math.abs;
import static java.lang.Math.max;
Line 2,600 ⟶ 2,690:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,610 ⟶ 2,700:
===ES5===
Iterative:
<langsyntaxhighlight lang="javascript">function levenshtein(a, b) {
var t = [], u, i, j, m = a.length, n = b.length;
if (!m) { return n; }
Line 2,640 ⟶ 2,730:
console.log('levenstein("' + a + '","' + b + '") was ' + d + ' should be ' + t);
}
});</langsyntaxhighlight>
 
===ES6===
Line 2,646 ⟶ 2,736:
 
By composition of generic functions:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,788 ⟶ 2,878:
// MAIN ---
return JSON.stringify(main())
})();</langsyntaxhighlight>
{{Out}}
<pre>[3, 3, 8, 8]</pre>
Line 2,805 ⟶ 2,895:
67ms for rosettacode/raisethysword
71ms for edocattesor/drowsyhtesiar
<syntaxhighlight lang="jq">
<lang jq>
# lookup the distance between s and t in the nested cache,
# which uses basic properties of the Levenshtein distance to save space:
Line 2,856 ⟶ 2,946:
 
def levenshteinDistance(s;t):
s as $s | t as $t | {} | ld($s;$t) | .[0];</langsyntaxhighlight>
'''Task'''
<langsyntaxhighlight lang="jq">def demo:
"levenshteinDistance between \(.[0]) and \(.[1]) is \( levenshteinDistance(.[0]; .[1]) )";
Line 2,865 ⟶ 2,955:
(["edocattesor", "drowsyhtesiar"] | demo),
(["this_algorithm_is_similar_to",
"Damerau-Levenshtein_distance"] | demo)</langsyntaxhighlight>
{{Out}}
levenshteinDistance between kitten and sitting is 3
Line 2,874 ⟶ 2,964:
=={{header|Jsish}}==
From Javascript, ES5 entry.
<langsyntaxhighlight lang="javascript">/* Levenshtein Distance, in Jsish */
 
function levenshtein(a, b) {
Line 2,918 ⟶ 3,008:
levenshtein('mississippi', 'swiss miss') ==> 8
=!EXPECTEND!=
*/</langsyntaxhighlight>
{{out}}
<pre>prompt$ jsish -u levenshtein.jsi
Line 2,927 ⟶ 3,017:
'''Recursive''':
{{works with|Julia|1.0}}
<langsyntaxhighlight lang="julia">function levendist(s::AbstractString, t::AbstractString)
ls, lt = length.((s, t))
ls == 0 && return lt
Line 2,938 ⟶ 3,028:
 
@show levendist("kitten", "sitting") # 3
@show levendist("rosettacode", "raisethysword") # 8</langsyntaxhighlight>
 
'''Iterative''':
{{works with|Julia|0.6}}
<langsyntaxhighlight lang="julia">function levendist1(s::AbstractString, t::AbstractString)
ls, lt = length(s), length(t)
if ls > lt
Line 2,962 ⟶ 3,052:
end
return dist[end]
end</langsyntaxhighlight>
 
Let's see some benchmark:
<langsyntaxhighlight lang="julia">using BenchmarkTools
println("\n# levendist(kitten, sitting)")
s, t = "kitten", "sitting"
Line 2,977 ⟶ 3,067:
@btime levendist(s, t)
println(" - Iterative:")
@btime levendist1(s, t)</langsyntaxhighlight>
 
{{out}}
Line 2,995 ⟶ 3,085:
=={{header|Kotlin}}==
===Standard Version===
<langsyntaxhighlight lang="scala">// version 1.0.6
 
// Uses the "iterative with two matrix rows" algorithm referred to in the Wikipedia article.
Line 3,027 ⟶ 3,117:
println("'rosettacode' to 'raisethysword' => ${levenshtein("rosettacode", "raisethysword")}")
println("'sleep' to 'fleeting' => ${levenshtein("sleep", "fleeting")}")
}</langsyntaxhighlight>
 
{{out}}
Line 3,037 ⟶ 3,127:
 
===Functional/Folding Version===
<langsyntaxhighlight lang="scala">
fun levenshtein(s: String, t: String,
charScore : (Char, Char) -> Int = { c1, c2 -> if (c1 == c2) 0 else 1}) : Int {
Line 3,057 ⟶ 3,147:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,071 ⟶ 3,161:
Suitable for short strings:
 
<langsyntaxhighlight lang="lisp">
(defun levenshtein-simple
(('() str)
Line 3,085 ⟶ 3,175:
(levenshtein-simple str1-tail str2)
(levenshtein-simple str1-tail str2-tail))))))
</syntaxhighlight>
</lang>
 
You can copy and paste that function into an LFE REPL and run it like so:
 
<langsyntaxhighlight lang="lisp">
> (levenshtein-simple "a" "a")
0
Line 3,098 ⟶ 3,188:
> (levenshtein-simple "kitten" "sitting")
3
</syntaxhighlight>
</lang>
 
It is not recommended to test strings longer than the last example using this implementation, as performance quickly degrades.
Line 3,104 ⟶ 3,194:
=== Cached Implementation ===
 
<langsyntaxhighlight lang="lisp">
(defun levenshtein-distance (str1 str2)
(let (((tuple distance _) (levenshtein-distance
Line 3,131 ⟶ 3,221:
(len (+ 1 (lists:min (list l1 l2 l3)))))
(tuple len (dict:store (tuple str1 str2) len c3)))))))
</syntaxhighlight>
</lang>
 
As before, here's some usage in the REPL. Note that longer strings are now possible to compare without incurring long execution times:
 
<langsyntaxhighlight lang="lisp">
> (levenshtein-distance "a" "a")
0
Line 3,146 ⟶ 3,236:
> (levenshtein-distance "rosettacode" "raisethysword")
8
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">'Levenshtein Distance translated by Brandon Parker
'08/19/10
'from http://www.merriampark.com/ld.htm#VB
Line 3,194 ⟶ 3,284:
Next i
LevenshteinDistance = d(n, m)
End Function </langsyntaxhighlight>
 
=={{header|Limbo}}==
{{trans|Go}}
<langsyntaxhighlight lang="limbo">implement Levenshtein;
 
include "sys.m"; sys: Sys;
Line 3,245 ⟶ 3,335:
return a + 1;
}
</syntaxhighlight>
</lang>
 
{{outputout}}
<codepre>
% levenshtein kitten sitting rosettacode raisethysword
kitten <-> sitting => 3
rosettacode <-> raisethysword => 8
</codepre>
 
=={{header|LiveCode}}==
{{trans|Go}}
<syntaxhighlight lang="livecode">
<lang LiveCode>
//Code By Neurox66
function Levenshtein pString1 pString2
Line 3,280 ⟶ 3,370:
put Levenshtein("kitten","sitting")
put Levenshtein("rosettacode","raisethysword")
</syntaxhighlight>
</lang>
{{out}}
<pre>3
Line 3,287 ⟶ 3,377:
=={{header|Lobster}}==
{{trans|C}}
<langsyntaxhighlight Lobsterlang="lobster">def levenshtein(s: string, t: string) -> int:
 
def makeNxM(n: int, m: int, v: int) -> [[int]]:
Line 3,322 ⟶ 3,412:
 
assert 3 == levenshtein("kitten", "sitting")
assert 8 == levenshtein("rosettacode", "raisethysword")</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function leven(s,t)
if s == '' then return t:len() end
if t == '' then return s:len() end
Line 3,344 ⟶ 3,434:
 
print(leven("kitten", "sitting"))
print(leven("rosettacode", "raisethysword"))</langsyntaxhighlight>
{{out}}
<pre>3
Line 3,350 ⟶ 3,440:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ Iterative with two matrix rows
Line 3,417 ⟶ 3,507:
}
Checkit2
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
> with(StringTools):
> Levenshtein("kitten","sitting");
Line 3,427 ⟶ 3,517:
> Levenshtein("rosettacode","raisethysword");
8
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">EditDistance["kitten","sitting"]
EditDistance["rosettacode","raisethysword"]</langsyntaxhighlight>
{{out}}
<pre>3
Line 3,437 ⟶ 3,527:
 
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
<lang MATLAB>
function score = levenshtein(s1, s2)
% score = levenshtein(s1, s2)
Line 3,468 ⟶ 3,558:
score = current_row(end);
end
</syntaxhighlight>
</lang>
Source : [https://github.com/benhamner/Metrics/blob/master/MATLAB/metrics/levenshtein.m]
 
=={{header|MiniScript}}==
In the Mini Micro environment, this function is part of the stringUtil library module, and can be used like so:
<langsyntaxhighlight MiniScriptlang="miniscript">import "stringUtil"
print "kitten".editDistance("sitting")</langsyntaxhighlight>
 
In environments where the stringUtil module is not available, you'd have to define it yourself:
<langsyntaxhighlight MiniScriptlang="miniscript">string.editDistance = function(s2)
n = self.len
m = s2.len
Line 3,516 ⟶ 3,606:
end function
 
print "kitten".editDistance("sitting")</langsyntaxhighlight>
 
{{out}}
'''Output:'''
<pre>3</pre>
 
 
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE LevenshteinDistance;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
Line 3,576 ⟶ 3,664:
ShowDistance("kitten", "sitting");
ShowDistance("rosettacode", "raisethysword");
END LevenshteinDistance.</langsyntaxhighlight>
{{out}}
<pre>kitten -> sitting: 3
Line 3,583 ⟶ 3,671:
=={{header|NetRexx}}==
{{trans|ooRexx}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,635 ⟶ 3,723:
 
return d[m + 1, n + 1]
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 3,644 ⟶ 3,732:
=={{header|Nim}}==
Nim provides a function in module "std/editdistance" to compute the Levenshtein distance between two strings containing ASCII characters only or containing UTF-8 encoded Unicode runes.
<langsyntaxhighlight lang="nim">import std/editdistance
 
echo editDistanceAscii("kitten", "sitting")
echo editDistanceAscii("rosettacode", "raisethysword")</langsyntaxhighlight>
 
{{out}}
Line 3,655 ⟶ 3,743:
{{trans|Python}}
Here is a translation of the Python version.
<langsyntaxhighlight lang="nim">import sequtils
 
func min(a, b, c: int): int {.inline.} = min(a, min(b, c))
Line 3,679 ⟶ 3,767:
 
echo levenshteinDistance("kitten","sitting")
echo levenshteinDistance("rosettacode","raisethysword")</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{trans|Modula-2}}
<syntaxhighlight lang="oberon2">MODULE LevesteinDistance;
 
IMPORT Out,Strings;
PROCEDURE Levestein(s,t:ARRAY OF CHAR):LONGINT;
CONST
maxlen = 15;
VAR
d:ARRAY maxlen,maxlen OF LONGINT;
lens,lent,i,j:LONGINT;
PROCEDURE Min(a,b:LONGINT):LONGINT;
BEGIN
IF a < b THEN RETURN a ELSE RETURN b END
END Min;
BEGIN
lens := Strings.Length(s);
lent := Strings.Length(t);
IF lens = 0 THEN RETURN lent
ELSIF lent = 0 THEN RETURN lens
ELSE
FOR i := 0 TO lens DO d[i,0] := i END;
FOR j := 0 TO lent DO d[0,j] := j END;
FOR i := 1 TO lens DO
FOR j := 1 TO lent DO
IF s[i-1] = t[j-1] THEN
d[i,j] := d[i-1,j-1]
ELSE
d[i,j] := Min((d[i-1,j] + 1),
Min(d[i,j-1] + 1, d[i-1,j-1] + 1));
END
END
END
END;
RETURN d[lens,lent];
END Levestein;
 
PROCEDURE ShowDistance(s,t:ARRAY OF CHAR);
BEGIN
Out.String(s);
Out.String(" -> ");
Out.String(t);
Out.String(": ");
Out.Int(Levestein(s,t),0);
Out.Ln
END ShowDistance;
BEGIN
ShowDistance("kitten", "sitting");
ShowDistance("rosettacode", "raisethysword");
END LevesteinDistance.
</syntaxhighlight>
 
{{out}}
<pre>kitten -> sitting: 3
rosettacode -> raisethysword: 8
</pre>
 
=={{header|Objeck}}==
{{trans|C#}}
<langsyntaxhighlight lang="objeck">class Levenshtein {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 2) {
Line 3,716 ⟶ 3,865:
return d[s->Size(), t->Size()];
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Translation of the C# code into a NSString category
<langsyntaxhighlight lang="objc">@interface NSString (levenshteinDistance)
- (NSUInteger)levenshteinDistanceToString:(NSString *)string;
@end
Line 3,754 ⟶ 3,903:
return r;
}
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
Translation of the pseudo-code of the Wikipedia article:
<langsyntaxhighlight lang="ocaml">let minimum a b c =
min a (min b c)
 
Line 3,798 ⟶ 3,947:
test "kitten" "sitting";
test "rosettacode" "raisethysword";
;;</langsyntaxhighlight>
=== A recursive functional version ===
This could be made faster with memoization
<langsyntaxhighlight OCamllang="ocaml">let levenshtein s t =
let rec dist i j = match (i,j) with
| (i,0) -> i
Line 3,817 ⟶ 3,966:
let () =
test "kitten" "sitting";
test "rosettacode" "raisethysword";</langsyntaxhighlight>
{{out}}
<pre>
Line 3,825 ⟶ 3,974:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
say "kitten -> sitting:" levenshteinDistance("kitten", "sitting")
say "rosettacode -> raisethysword:" levenshteinDistance("rosettacode", "raisethysword")
Line 3,872 ⟶ 4,021:
 
return d[m + 1, n + 1 ]
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,882 ⟶ 4,031:
{{trans|JavaScript}}
{{Works with|PARI/GP|2.7.4 and above}}
<langsyntaxhighlight lang="parigp">
\\ Levenshtein distance between two words
\\ 6/21/16 aev
Line 3,906 ⟶ 4,055:
levensDist("X","oX");
}
</langsyntaxhighlight>
{{Output}}
Line 3,920 ⟶ 4,069:
=={{header|Pascal}}==
A fairly direct translation of the wikipedia pseudo code:
<langsyntaxhighlight lang="pascal">Program LevenshteinDistanceDemo(output);
 
uses
Line 3,957 ⟶ 4,106:
s2 := 'raisethysword';
writeln('The Levenshtein distance between "', s1, '" and "', s2, '" is: ', LevenshteinDistance(s1, s2));
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,966 ⟶ 4,115:
=={{header|Perl}}==
Recursive algorithm, as in the C sample. You are invited to comment out the line where it says so, and see the speed difference. By the way, there's the <code>Memoize</code> standard module, but it requires setting quite a few parameters to work right for this example, so I'm just showing the simple minded caching scheme here.
<langsyntaxhighlight Perllang="perl">use List::Util qw(min);
 
my %cache;
Line 3,990 ⟶ 4,139:
}
 
print leven('rosettacode', 'raisethysword'), "\n";</langsyntaxhighlight>
 
Iterative solution:
 
<langsyntaxhighlight lang="perl">use List::Util qw(min);
 
sub leven {
Line 4,016 ⟶ 4,165:
}
 
print leven('rosettacode', 'raisethysword'), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,060 ⟶ 4,209:
<span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,074 ⟶ 4,223:
=== alternative ===
Modelled after the Processing code, uses a single/smaller array, passes the same tests as above.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">levenshtein</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">costs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
Line 4,089 ⟶ 4,238:
<span style="color: #008080;">return</span> <span style="color: #000000;">costs</span><span style="color: #0000FF;">[$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
echo levenshtein('kitten','sitting');
echo levenshtein('rosettacode', 'raisethysword');
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,102 ⟶ 4,251:
 
=={{header|Picat}}==
===Iterative===
Based on the iterative algorithm at Wikipedia. Picat is 1-based so some adjustments are needed.
<langsyntaxhighlight Picatlang="picat">levenshtein(S,T) = Dist =>
M = 1+S.length,
N = 1+T.length,
Line 4,129 ⟶ 4,278:
end,
 
Dist = D[M,N].</langsyntaxhighlight>
 
===Tabled recursive version===
<langsyntaxhighlight Picatlang="picat">table
levenshtein_rec(S,T) = Dist =>
Dist1 = 0,
Line 4,149 ⟶ 4,298:
Dist1 := A + 1
end,
Dist = Dist1.</langsyntaxhighlight>
 
===Mode-directed tabling===
{{trans|Prolog}}
<syntaxhighlight lang="picat">
<lang Picat>
levenshtein_mode(S,T) = Dist =>
lev(S, T, Dist).
Line 4,162 ⟶ 4,311:
lev([_|L], [_|R], D) :- lev(L, R, H), D is H+1.
lev([_|L], R, D) :- lev(L, R, H), D is H+1.
lev(L, [_|R], D) :- lev(L, R, H), D is H+1.</langsyntaxhighlight>
 
 
===Test===
<langsyntaxhighlight Picatlang="picat">go =>
S = [
Line 4,184 ⟶ 4,333:
nl
end,
nl.</langsyntaxhighlight>
 
{{out}}
Line 4,215 ⟶ 4,364:
===Benchmark on larger strings===
Benchmarking the methods with larger strings of random lengths (between 1 and 2000).
<langsyntaxhighlight Picatlang="picat">go2 =>
_ = random2(),
Len = 2000,
Line 4,238 ⟶ 4,387:
Alpha = "abcdefghijklmnopqrstuvxyz",
Len = Alpha.length,
S := [Alpha[random(1,Len)] : _ in 1..random(1,MaxLen)].</langsyntaxhighlight>
 
Here is sample run. The version using mode-directed tabling is clearly the fastest.
Line 4,258 ⟶ 4,407:
=={{header|PicoLisp}}==
Translation of the pseudo-code in the Wikipedia article:
<langsyntaxhighlight PicoLisplang="picolisp">(de levenshtein (A B)
(let D
(cons
Line 4,275 ⟶ 4,424:
(get D J (inc I))
(get D (inc J) I)
(get D J I) ) ) ) ) ) ) ) )</langsyntaxhighlight>
or, using 'map' to avoid list indexing:
<langsyntaxhighlight PicoLisplang="picolisp">(de levenshtein (A B)
(let D
(cons
Line 4,296 ⟶ 4,445:
(cadr Y) ) )
B
D ) ) )</langsyntaxhighlight>
{{out|Output (both cases)}}
<pre>: (levenshtein (chop "kitten") (chop "sitting"))
Line 4,303 ⟶ 4,452:
=={{header|PL/I}}==
===version 1===
<langsyntaxhighlight lang="pli">*process source xref attributes or(!);
lsht: Proc Options(main);
Call test('kitten' ,'sitting');
Line 4,358 ⟶ 4,507:
Return(ld);
End;
End;</langsyntaxhighlight>
{{out}}
<pre> 1st string = >kitten<
Line 4,384 ⟶ 4,533:
Levenshtein distance = 3</pre>
===version 2 recursive with memoization===
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
ld3: Proc Options(main);
Dcl ld(0:30,0:30) Bin Fixed(31);
Line 4,428 ⟶ 4,577:
Return(ld(sl,tl));
End;
End;</langsyntaxhighlight>
Output is the same as for version 1.
 
=={{header|PL/M}}==
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
{{Trans|Action!}}
<syntaxhighlight lang="pli">100H: /* CALCULATE THE LEVENSHTEIN DISTANCE BETWEEN STRINGS */
/* TRANS:ATED FROM THE ACTION! SAMPLE */
 
/* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
 
DECLARE WIDTH LITERALLY '17'; /* ALLOW STRINGS UP TO 16 CHARACTERS */
DECLARE MATRIX$SIZE LITERALLY '289'; /* 17*17 ELEMENTS */
DECLARE STRING LITERALLY '( WIDTH )BYTE';
SCOPY: PROCEDURE( WORD, STR ); /* CONVEET PL/M STYLE STRING TO ACTION! */
DECLARE ( WORD, STR ) ADDRESS;
DECLARE ( W BASED WORD, S BASED STR ) STRING;
DECLARE ( I, C ) BYTE;
 
I = 0;
DO WHILE( ( C := S( I ) ) <> '$' );
W( I := I + 1 ) = C;
END;
W( 0 ) = I;
END SCOPY;
 
SET2DM: PROCEDURE( MATRIX, X, Y, VAL );
DECLARE ( MATRIX, X, Y, VAL ) ADDRESS;
DECLARE M BASED MATRIX ( MATRIX$SIZE )ADDRESS;
M( X + ( Y * WIDTH ) ) = VAL;
END SET2DM;
GET2DM: PROCEDURE( MATRIX, X, Y )ADDRESS;
DECLARE ( MATRIX, X, Y, VAL ) ADDRESS;
DECLARE M BASED MATRIX ( MATRIX$SIZE )ADDRESS;
RETURN M( X + ( Y * WIDTH ) );
END GET2DM;
LEVENSHTEIN$DISTANCE: PROCEDURE( S1, S2 )ADDRESS;
DECLARE ( S1, S2 ) ADDRESS;
DECLARE STR1 BASED S1 STRING, STR2 BASED S2 STRING;
DECLARE MATRIX ( MATRIX$SIZE ) ADDRESS;
DECLARE ( MIN, K, L, I, J, M, N ) BYTE;
M = STR1( 0 );
N = STR2( 0 );
DO I = 0 TO MATRIX$SIZE - 1; MATRIX( I ) = 0; END;
DO I = 0 TO M; CALL SET2DM( .MATRIX, I, 1, I ); END;
DO J = 0 TO N; CALL SET2DM( .MATRIX, 1, J, J ); END;
DO J = 1 TO N;
DO I = 1 TO M;
IF STR1( I ) = STR2( J ) THEN DO;
CALL SET2DM( .MATRIX, I, J, GET2DM( .MATRIX, I - 1, J - 1 ) );
END;
ELSE DO;
MIN = GET2DM( .MATRIX, I - 1, J ) + 1; /* DELETION */
K = GET2DM( .MATRIX, I, J - 1 ) + 1; /* INSERTION */
L = GET2DM( .MATRIX, I - 1, J - 1 ) + 1; /* SUBSTITUTION */
IF K < MIN THEN MIN = K;
IF L < MIN THEN MIN = L;
CALL SET2DM( .MATRIX, I, J, MIN );
END;
END;
END;
RETURN GET2DM( .MATRIX, M, N );
END LEVENSHTEIN$DISTANCE;
 
TEST: PROCEDURE( W1, W2 );
DECLARE ( W1, W2 ) ADDRESS;
DECLARE ( WORD$1, WORD$2 ) STRING;
 
CALL SCOPY( .WORD$1, W1 );
CALL SCOPY( .WORD$2, W2 );
 
CALL PR$STRING( W1 ); CALL PR$STRING( .' -> $' ); CALL PR$STRING( W2 );
CALL PR$STRING( .', LEVENSHTEIN DISTANCE: $' );
CALL PR$NUMBER( LEVENSHTEIN$DISTANCE( .WORD$1, .WORD$2 ) );
CALL PR$NL;
END TEST;
 
/* TEST CASES */
CALL TEST( .'KITTEN$', .'SITTING$' );
CALL TEST( .'ROSETTACODE$', .'RAISETHYSWORD$' );
CALL TEST( .'QWERTY$', .'QWERYT$' );
CALL TEST( .( 'ACTION', 33, '$' ), .'PL/M$' );
 
EOF</syntaxhighlight>
{{out}}
<pre>
KITTEN -> SITTING, LEVENSHTEIN DISTANCE: 3
ROSETTACODE -> RAISETHYSWORD, LEVENSHTEIN DISTANCE: 8
QWERTY -> QWERYT, LEVENSHTEIN DISTANCE: 2
ACTION! -> PL/M, LEVENSHTEIN DISTANCE: 4
</pre>
 
=={{header|PowerShell}}==
This version does not allow empty strings.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-LevenshteinDistance
{
Line 4,493 ⟶ 4,753:
$outputObject
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-LevenshteinDistance "kitten" "sitting"
Get-LevenshteinDistance rosettacode raisethysword
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,507 ⟶ 4,767:
 
=={{header|Processing}}==
<langsyntaxhighlight lang="processing">void setup() {
println(distance("kitten", "sitting"));
}
Line 4,524 ⟶ 4,784:
}
return costs[b.length()];
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">def setup():
println(distance("kitten", "sitting"))
 
Line 4,544 ⟶ 4,804:
costs[j] = cj
 
return costs[len(b)]</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,550 ⟶ 4,810:
Works with SWI-Prolog.<br>
Based on Wikipedia's pseudocode.
<langsyntaxhighlight Prologlang="prolog">levenshtein(S, T, R) :-
length(S, M),
M1 is M+1,
Line 4,610 ⟶ 4,870:
 
init_n(N, L) :-
nth0(0, L, N).</langsyntaxhighlight>
{{out|Output examples}}
<pre> ?- levenshtein("kitten", "sitting", R).
Line 4,640 ⟶ 4,900:
=={{header|PureBasic}}==
Based on Wikipedia's pseudocode.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure LevenshteinDistance(A_string$, B_String$)
Protected m, n, i, j, min, k, l
m = Len(A_string$)
Line 4,668 ⟶ 4,928:
;- Testing
n = LevenshteinDistance("kitten", "sitting")
MessageRequester("Info","Levenshtein Distance= "+Str(n))</langsyntaxhighlight>
 
=={{header|Python}}==
===Iterative 1===
Faithful implementation of "Iterative with full matrix" from Wikipedia
<langsyntaxhighlight lang="python">def levenshteinDistance(str1, str2):
m = len(str1)
n = len(str2)
Line 4,690 ⟶ 4,950:
 
print(levenshteinDistance("kitten","sitting"))
print(levenshteinDistance("rosettacode","raisethysword"))</langsyntaxhighlight>
{{out}}
<pre>3
Line 4,697 ⟶ 4,957:
===Iterative 2===
Implementation of the Wikipedia algorithm, optimized for memory
<langsyntaxhighlight lang="python">def minimumEditDistance(s1,s2):
if len(s1) > len(s2):
s1,s2 = s2,s1
Line 4,714 ⟶ 4,974:
print(minimumEditDistance("kitten","sitting"))
print(minimumEditDistance("rosettacode","raisethysword"))</langsyntaxhighlight>
{{out}}
<pre>3
Line 4,721 ⟶ 4,981:
===Iterative 3===
Iterative space optimized (even bounded)
<langsyntaxhighlight lang="python">def ld(a, b, mx=-1):
def result(d): return d if mx < 0 else False if d > mx else True
Line 4,762 ⟶ 5,022:
ld('kitten','kittenaaaaaaaaaaaaaaaaa',3), # False
ld('kittenaaaaaaaaaaaaaaaaa','kitten',3) # False
)</langsyntaxhighlight>
{{out}}
<pre>0 1 2 3 4 8 17 17
Line 4,770 ⟶ 5,030:
====Memoized recursion====
(Uses [http://docs.python.org/dev/library/functools.html?highlight=functools.lru_cache#functools.lru_cache this] cache from the standard library).
<langsyntaxhighlight lang="python">>>> from functools import lru_cache
>>> @lru_cache(maxsize=4095)
def ld(s, t):
Line 4,782 ⟶ 5,042:
 
>>> print( ld("kitten","sitting"),ld("rosettacode","raisethysword") )
3 8</langsyntaxhighlight>
 
====Non-recursive: reduce and scanl====
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Levenshtein distance'''
 
from itertools import (accumulate, chain, islice)
Line 4,932 ⟶ 5,192:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Levenshtein minimum edit distances:
Line 4,945 ⟶ 5,205:
=={{header|Racket}}==
A memoized recursive implementation.
<langsyntaxhighlight lang="racket">#lang racket
 
(define (levenshtein a b)
Line 4,964 ⟶ 5,224:
 
(levenshtein "kitten" "sitting")
(levenshtein "rosettacode" "raisethysword")</langsyntaxhighlight>
{{out}}
<pre>3
Line 4,971 ⟶ 5,231:
=={{header|Raku}}==
(formerly Perl 6)
 
{{works with|rakudo|2015-09-16}}
Implementation of the Wikipedia algorithm. Since column 0 and row 0 are used for base distances, the original algorithm would require us to compare "@s[$i-1] eq @t[$j-1]", and reference $m and $n separately. Prepending an unused value (undef) onto @s and @t makes their indices align with the $i,$j numbering of @d, and lets us use .end instead of $m,$n.
<syntaxhighlight lang="raku" perl6line>sub levenshtein-distance ( Str $s, Str $t --> Int ) {
my @s = *, |$s.comb;
my @t = *, |$t.comb;
Line 4,990 ⟶ 5,250:
}
 
return @d[*-1][*-1];
}
 
myfor @a = [<kitten sitting>], [<saturday sunday>], [<rosettacode raisethysword>]; -> ($s, $t) {
say "Levenshtein distance('$s', '$t') == ", levenshtein-distance($s, $t)
 
}</syntaxhighlight>
for @a -> [$s, $t] {
say "Levenshtein distance('$s', '$t') == ", levenshtein-distance($s, $t);
}</lang>
{{out}}
<pre>Levenshtein distance('kitten', 'sitting') == 3
Levenshtein distance('saturday', 'sunday') == 3
Levenshtein distance('rosettacode', 'raisethysword') == 8</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Show ('kitten') ('sitting')>
<Show ('rosettacode') ('raisethysword')>;
};
 
Show {
(e.A) (e.B) = <Prout e.A ' -> ' e.B ': ' <Lev (e.A) (e.B)>>;
};
 
Lev {
(e.A) (), <Lenw e.A>: s.L e.A = s.L;
() (e.B), <Lenw e.B>: s.L e.B = s.L;
(s.C e.A) (s.C e.B) = <Lev (e.A) (e.B)>;
(e.A) (e.B), e.A: s.HA e.LA, e.B: s.HB e.LB =
<+ 1 <Min <Lev (e.LA) (e.B)>
<Lev (e.A) (e.LB)>
<Lev (e.LA) (e.LB)>>>;
}
 
Min {
s.N = s.N;
s.M s.N e.X, <Compare s.M s.N>: {
'-' = <Min s.M e.X>;
s.X = <Min s.N e.X>;
};
};</syntaxhighlight>
{{out}}
<pre>kitten -> sitting: 3
rosettacode -> raisethysword: 8</pre>
 
=={{header|REXX}}==
===version 1===
As per the task's requirements, this version includes a driver to display the results.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the Levenshtein distance between two strings. */
call Levenshtein 'kitten' , "sitting"
call Levenshtein 'rosettacode' , "raisethysword"
Line 5,025 ⟶ 5,314:
end /*k*/
end /*j*/ /* [↑] best choice.*/
say ' Levenshtein distance = ' @.oL.tL; say; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 5,051 ⟶ 5,340:
===version 2===
<strike>same as</strike> Similar to version 1 <strike>(but does not include a driver for testing)</strike>, reformatted and commented
<langsyntaxhighlight lang="rexx">
/*rexx*/
 
Line 5,105 ⟶ 5,394:
say 'Levenshtein distance = ' d.m.n; say ''
Return d.m.n
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 5,159 ⟶ 5,448:
===version 3===
Alternate algorithm from Wikipedia <strike>(but does not include a driver for testing)</strike>.
<langsyntaxhighlight lang="rexx">
/*rexx*/
 
Line 5,205 ⟶ 5,494:
End
return v1.tl
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 5,235 ⟶ 5,524:
===version 4 (recursive)===
Recursive algorithm from Wikipedia with memoization
<langsyntaxhighlight lang="rexx">
/*rexx*/
 
Line 5,278 ⟶ 5,567:
End
Return ld.sl.tl
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 5,307 ⟶ 5,596:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Levenshtein distance
 
Line 5,347 ⟶ 5,636:
levenshteindistance = d[n][m]
return levenshteindistance
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,353 ⟶ 5,642:
distance(saturday, sunday) = 3
distance(rosettacode, raisethysword) = 8
</pre>
 
=={{header|RPL}}==
{{works with|HP|28}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ DUP2 SIZE SWAP SIZE → a b lb la
≪ '''IF''' la lb * NOT '''THEN''' la lb +
'''ELSE'''
a 2 la SUB b 2 lb SUB DUP2 <span style="color:blue">LEV</span>
'''IF''' a 1 1 SUB b 1 1 SUB == '''THEN'''
ROT ROT DROP2
'''ELSE'''
a ROT <span style="color:blue">LEV</span> ROT b <span style="color:blue">LEV</span>
MIN MIN 1 +
'''END END'''
≫ ≫ '<span style="color:blue">LEV</span>' STO
|
<span style="color:blue">LEV</span> ''( "a" "b" → distance )''
if |a|=0 or [b|=0 then return resp. [b| or |a|
else
put tail(a), tail(b) and lev(tail(a),tail(b)) in stack
if a[1]=b[1} then
clean stack and return lev(tail(a),tail(b))
else
put lev(a,tail(b)) and lev(tail(a),b) in stack
return min of the 3 values in stack and add 1
|}
"kitten" "sitting" <span style="color:blue">LEV</span>
"Summer" "Winter" <span style="color:blue">LEV</span>
"Levenshtein" "Levenshtein" <span style="color:blue">LEV</span>
{{out}}
<pre>
3: 3
2: 4
1: 0
</pre>
 
===Iterative implementation (Wagner-Fischer algorithm)===
 
index of arrays and strings start with 1 in RPL, so the main trick in translating the algorithm given by Wikipedia was to manage the offsets properly. The distance between "rosettacode" and "raisethysword" is within the reach of a calculator (emulated or not), unlike the above recursive approach.
{{works with|HP|48}}
{| class="wikitable"
! RPL code
! Comment
|-
|
DUP2 { } + + ≪ SIZE ≫ DOLIST 1 ADD 0 CON → a b d
≪ 1 a SIZE '''FOR''' h
'd' h 1 + 1 2 →LIST h PUT '''NEXT'''
1 b SIZE '''FOR''' j
'd' 1 j 1 + 2 →LIST j PUT '''NEXT'''
1 b SIZE '''FOR''' j
1 a SIZE '''FOR''' h
a h DUP SUB b j DUP SUB ≠
'd' h j 2 →LIST GET +
'd' h j 1 + 2 →LIST GET 1 +
'd' h 1 + j 2 →LIST GET 1 +
MIN MIN 'd' h 1 + j 1 + 2 →LIST ROT PUT
'''NEXT NEXT'''
'd' DUP SIZE GET
≫ ≫ '<span style="color:blue">LEV2</span>' STO
|
<span style="color:blue">LEV2</span> ''( "a" "b" → distance )''
declare int d[0..m, 0..n] and set each element in d to zero
for h from 1 to m: <span style="color:grey>// h replaces i, which is √-1 in RPL</span>
d[h, 0] := i <span style="color:grey>// RPL array indexes start with 1</span>
for j from 1 to n:
d[0, j] := j
for j from 1 to n:
for h from 1 to m:
substitutionCost := ( s[h] <> t[j] )
d[h, j] := minimum(d[h-1, j-1] + substitutionCost,
d[h-1, j] + 1,
d[h, j-1] + 1)
return d[m, n]
|}
"rosettacode" "raisethysword" <span style="color:blue">LEV2</span>
{{out}}
<pre>
1: 8
</pre>
 
Line 5,360 ⟶ 5,739:
and for <code>k >= j</code> contains ''lev(i-1, k)''. The inner loop body restores the invariant for the
new value of <code>j</code>.
<langsyntaxhighlight lang="ruby">module Levenshtein
def self.distance(a, b)
Line 5,382 ⟶ 5,761:
end
 
Levenshtein.test</langsyntaxhighlight>
{{out}}
<pre>
Line 5,391 ⟶ 5,770:
A variant can be found used in Rubygems [https://github.com/rubygems/rubygems/blob/master/lib/rubygems/text.rb]
 
<langsyntaxhighlight lang="ruby">def levenshtein_distance(str1, str2)
n = str1.length
m = str2.length
Line 5,424 ⟶ 5,803:
%w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b|
puts "distance(#{a}, #{b}) = #{levenshtein_distance(a, b)}"
end</langsyntaxhighlight>
same output
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print levenshteinDistance("kitten", "sitting")
print levenshteinDistance("rosettacode", "raisethysword")
end
Line 5,459 ⟶ 5,838:
levenshteinDistance = d(n, m)
[ex]
end function</langsyntaxhighlight>Output:<pre>3
8</pre>
 
Line 5,465 ⟶ 5,844:
Implementation of the wikipedia algorithm.
{{works with|Rust|1.45}}
<langsyntaxhighlight lang="rust">fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
Line 5,496 ⟶ 5,875:
}
matrix[word2_length-1][word1_length-1]
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 5,504 ⟶ 5,883:
=={{header|Scala}}==
===Translated Wikipedia algorithm.===
<langsyntaxhighlight lang="scala">object Levenshtein0 extends App {
 
def distance(s1: String, s2: String): Int = {
Line 5,527 ⟶ 5,906:
printDistance("rosettacode", "raisethysword")
 
}</langsyntaxhighlight>
{{out}}
<pre>kitten -> sitting : 3
Line 5,533 ⟶ 5,912:
===Functional programmed, memoized===
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/zj7bHC7/0 (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/qHhDWl68QgWv1uwOYzzNqw Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import scala.collection.mutable
import scala.collection.parallel.ParSeq
 
Line 5,566 ⟶ 5,945:
printDistance("sleep", "fleeting")
 
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 5,572 ⟶ 5,951:
Recursive version from wikipedia article.
 
<langsyntaxhighlight lang="scheme">
(define (levenshtein s t)
(define (%levenshtein s sl t tl)
Line 5,586 ⟶ 5,965:
(string->list t)
(string-length t)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,597 ⟶ 5,976:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: levenshteinDistance (in string: s, in string: t) is func
Line 5,628 ⟶ 6,007:
writeln("kitten -> sitting: " <& levenshteinDistance("kitten", "sitting"));
writeln("rosettacode -> raisethysword: " <& levenshteinDistance("rosettacode", "raisethysword"));
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,638 ⟶ 6,017:
=={{header|SenseTalk}}==
SenseTalk has a built-in TextDifference function for this.
<syntaxhighlight lang="sensetalk">
<lang SenseTalk>
put textDifference("kitten", "sitting") // --> 3
put textDifference("rosettacode", "raisethysword") // --> 8
 
</syntaxhighlight>
</lang>
 
=={{header|SequenceL}}==
This implementation is based on the "Iterative with two matrix rows" version on Wikipedia.
<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;
Line 5,668 ⟶ 6,047:
min(min(v1[n] + 1, v0[n + 1] + 1), v0[n] + (0 when s = t[n] else 1))),
n + 1);
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
===Recursive===
<langsyntaxhighlight lang="ruby">func lev(s, t) is cached {
 
s || return t.len
t || return s.len
 
var s1 = s.ftslice(1)
var t1 = t.ftslice(1)
 
s[0] == t[0] ? __FUNC__(s1, t1)
Line 5,686 ⟶ 6,065:
__FUNC__(s1, t )
)
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="ruby">func lev(s, t) {
var d = [@(0 .. t.len), s.len.of {[_]}...]
for i,j in (^s ~X ^t) {
Line 5,699 ⟶ 6,078:
}
d[-1][-1]
}</langsyntaxhighlight>
 
Calling the function:
<langsyntaxhighlight lang="ruby">say lev(%c'kitten', %c'sitting'); # prints: 3
say lev(%c'rosettacode', %c'raisethysword'); # prints: 8</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
INTEGER PROCEDURE LEVENSHTEINDISTANCE(S1, S2); TEXT S1, S2;
Line 5,742 ⟶ 6,121:
 
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,754 ⟶ 6,133:
{{works with|Smalltalk/X}}
ST/X provides a customizable levenshtein method in the String class (weights for individual operations can be passed in):
<langsyntaxhighlight lang="smalltalk">'kitten' levenshteinTo: 'sitting' s:1 k:1 c:1 i:1 d:1 -> 3
'rosettacode' levenshteinTo: 'raisethysword' s:1 k:1 c:1 i:1 d:1 -> 8</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 5,761 ⟶ 6,140:
Version using entire matrix:
 
<langsyntaxhighlight lang="swift">func levDis(w1: String, w2: String) -> Int {
let (t, s) = (w1.characters, w2.characters)
Line 5,775 ⟶ 6,154:
}
return mat.last!.last!
}</langsyntaxhighlight>
 
Version using only two rows at a time:
 
<langsyntaxhighlight lang="swift">func levDis(w1: String, w2: String) -> Int {
let (t, s) = (w1.characters, w2.characters)
Line 5,794 ⟶ 6,173:
}
return last.last!
}</langsyntaxhighlight>
 
===Single array version===
{{trans|C++}}
<langsyntaxhighlight lang="swift">func levenshteinDistance(string1: String, string2: String) -> Int {
let m = string1.count
let n = string2.count
Line 5,824 ⟶ 6,203:
}
 
print(levenshteinDistance(string1: "rosettacode", string2: "raisethysword"))</langsyntaxhighlight>
 
{{out}}
Line 5,832 ⟶ 6,211:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc levenshteinDistance {s t} {
# Edge cases
if {![set n [string length $t]]} {
Line 5,860 ⟶ 6,239:
# The score is at the end of the last-computed row
return [lindex $p end]
}</langsyntaxhighlight>
{{out|Usage}}
<langsyntaxhighlight lang="tcl">puts [levenshteinDistance "kitten" "sitting"]; # Prints 3</langsyntaxhighlight>
 
=={{header|TSE SAL}}==
<langsyntaxhighlight TSESALlang="tsesal">// library: math: get: damerau: levenshtein <description></description> <version>1.0.0.0.23</version> <version control></version control> (filenamemacro=getmadle.s) [kn, ri, th, 08-09-2011 23:04:55]
INTEGER PROC FNMathGetDamerauLevenshteinDistanceI( STRING s1, STRING s2 )
INTEGER L1 = Length( s1 )
Line 5,899 ⟶ 6,278:
s2 = "altruistic"
Warn( "Minimum amount of steps to convert ", s1, " to ", s2, " = ", FNMathGetDamerauLevenshteinDistanceI( s1, s2 ) ) // gives e.g. 6
END</langsyntaxhighlight>
 
=={{header|Turbo-Basic XL}}==
<langsyntaxhighlight lang="turbobasic">
10 DIM Word_1$(20), Word_2$(20), DLDm(21, 21)
11 CLS
Line 5,938 ⟶ 6,317:
11846 ? "Damerau Distance=";Result
11850 ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>kitten, sitting: 3
Line 5,945 ⟶ 6,324:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
distance=DISTANCE ("kitten", "sitting")
PRINT distance
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,957 ⟶ 6,336:
=={{header|TypeScript}}==
{{Trans|JavaScript}}
<langsyntaxhighlight lang="typescript">
function levenshtein(a: string, b: string): number {
const m: number = a.length,
Line 5,973 ⟶ 6,352:
}
 
</syntaxhighlight>
</lang>
 
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="ubasic-4th">
' Uses the "iterative with two matrix rows" algorithm
' referred to in the Wikipedia article.
 
' create two integer arrays of distances
Dim @u(128) ' previous
Dim @v(128) ' current
 
Print "'kitten' to 'sitting' => ";
Print FUNC(_Levenshtein ("kitten", "sitting"))
 
Print "'rosettacode' to 'raisethysword' => ";
Print FUNC(_Levenshtein ("rosettacode", "raisethysword"))
 
Print "'sleep' to 'fleeting' => ";
Print FUNC(_Levenshtein ("sleep", "fleeting"))
 
End
 
_Levenshtein
Param (2)
Local (3)
 
' degenerate cases
If Comp(a@, b@) = 0 Then Return (0)
If Len(a@) = 0 Then Return (Len(b@))
If Len(b@) = 0 Then Return (Len(a@))
 
' initialize v0
For c@ = 0 To Len(b@)
@u(c@) = c@
Next
 
For c@ = 0 To Len(a@) - 1
' calculate @v() from @u()
@v(0) = c@ + 1
For d@ = 0 To Len(b@) - 1
e@ = IIf(Peek (a@, c@) = Peek (b@, d@), 0, 1)
@v(d@ + 1) = min(@v(d@) + 1, Min(@u(d@ + 1) + 1, @u(d@) + e@))
Next
 
' copy @v() to @u() for next iteration
For d@ = 0 To Len(b@)
@u(d@) = @v(d@)
Next
Next
 
Return (@v(Len(b@)))
</syntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">class LevenshteinDistance : Object {
public static int compute (owned string s, owned string t, bool case_sensitive = false) {
var n = s.length;
Line 6,002 ⟶ 6,434:
}
}
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Option Base 1
Function levenshtein(s1 As String, s2 As String) As Integer
Dim n As Integer: n = Len(s1) + 1
Line 6,045 ⟶ 6,477:
Debug.Print levenshtein("kitten", "sitting")
Debug.Print levenshtein("rosettacode", "raisethysword")
End Sub</langsyntaxhighlight>{{out}}
<pre> 3
8 </pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Levenshtein distance - 23/04/2020
 
Function Min(a,b)
Line 6,093 ⟶ 6,525:
PrintLevenshtein "rosettacode", "raisethysword"
PrintLevenshtein "saturday", "sunday"
PrintLevenshtein "sleep", "fleeting"</langsyntaxhighlight>
{{out}}
<pre>
Line 6,110 ⟶ 6,542:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<langsyntaxhighlight lang="vb">Function min(x As Integer, y As Integer) As Integer
If x < y Then
min = x
Line 6,170 ⟶ 6,602:
Debug.Print "'sleep' to 'fleeting' => "; levenshtein("sleep", "fleeting")
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
<pre>'kitten' to 'sitting' => 3
'kitten' to 'sitting' => 3
'sitting' to 'kitten' => 3
'rosettacode' to 'raisethysword' => 8
'sleep' to 'fleeting' => 5</pre>
</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet"> Function LevenshteinDistance(ByVal String1 As String, ByVal String2 As String) As Integer
Dim Matrix(String1.Length, String2.Length) As Integer
Dim Key As Integer
Line 6,197 ⟶ 6,631:
Next
Return Matrix(String1.Length - 1, String2.Length - 1)
End Function</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import strings
 
fn main() {
println(strings.levenshtein_distance("kitten", "sitting"))
println(strings.levenshtein_distance("rosettacode", "raisethysword"))
}
</syntaxhighlight>
 
{{out}}
<pre>
3
8
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var levenshtein = Fn.new { |s, t|
var ls = s.count
var lt = t.count
Line 6,225 ⟶ 6,675:
}
 
System.print(levenshtein.call("kitten", "sitting"))</langsyntaxhighlight>
 
{{out}}
Line 6,231 ⟶ 6,681:
3
</pre>
 
=={{header|Zig}}==
{{trans|C}}
 
'''Works with:''' 0.11.x, 0.12.0-dev.1381+61861ef39
 
For 0.10.x, replace @min(a, b, c) with std.math.min3(a, b, c).
 
Recursive method without memoization.
 
<syntaxhighlight lang="zig">const std = @import("std");
 
fn levenshtein(s: []const u8, t: []const u8) usize {
// If either string is empty, difference is inserting all chars
// from the other
if (s.len == 0) return t.len;
if (t.len == 0) return s.len;
 
// If last letters are the same, the difference is whatever is
// required to edit the rest of the strings
if (s[s.len - 1] == t[t.len - 1])
return levenshtein(s[0 .. s.len - 1], t[0 .. t.len - 1]);
 
// Else try:
// changing last letter of s to that of t; or
// remove last letter of s; or
// remove last letter of t,
// any of which is 1 edit plus editing the rest of the strings
const a = levenshtein(s[0 .. s.len - 1], t[0 .. t.len - 1]);
const b = levenshtein(s, t[0 .. t.len - 1]);
const c = levenshtein(s[0 .. s.len - 1], t);
 
return @min(a, b, c) + 1;
}
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
 
const s1 = "rosettacode";
const s2 = "raisethysword";
try stdout_w.print("distance between '{s}' and '{s}': {d}\n", .{ s1, s2, levenshtein(s1, s2) });
return;
}</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn levenshtein(s1,s2){
sz2,costs:=s2.len() + 1, List.createLong(sz2,0); // -->zero filled List
foreach i in (s1.len() + 1){
Line 6,251 ⟶ 6,745:
}
costs[-1]
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach a,b in (T(T("kitten","sitting"), T("rosettacode","raisethysword"),
T("yo",""), T("","yo"), T("abc","abc")) ){
println(a," --> ",b,": ",levenshtein(a,b));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,266 ⟶ 6,760:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 REM ZX Spectrum Basic - Levenshtein distance
20 INPUT "first word:",n$
30 INPUT "second word:",m$
Line 6,279 ⟶ 6,773:
120 NEXT i
130 NEXT j
140 PRINT "The Levenshtein distance between """;n$;""", """;m$;""" is ";d(m+1,n+1);"."</langsyntaxhighlight>
{{out}}
<pre>
55

edits