Add preview of 1984-2019

The 2020 winners are hinted it, but the source code is not there,
nor are the hints. Someone could look into the HTML and
see what was commented out, but that is not a problem because
WHO won is known and the name of their AWARD is known already.
Moreover a number of the winners have talked about what their
entirs do, so the commented out spoiler text is not a bit problem.

One will find HTML commented out with:

    <!-- XXX remove when 2020 is ready
    2020 links here
    XXX remove when 2020 is ready -->

The "XXX remove when 2020 is ready" string is found at the
start and end comment blocks.  Again, soneone could read
what was commented out, but that is OK since most of that
information is known or can be known.  The following files
have such HTML comment blocks in them.

    ./winners.html
    ./years-spoiler.html
    ./years.html

In addition, ./all/summary.txt was modified to not
include the 2020 entries for the momemt.

The 2020 winner code AND write-ups are NOT part of this set.

p.s. The all/all.tar.bz2 does not contain the 2020 source code (yet?).
This commit is contained in:
Landon Curt Noll committed 2020-12-30 16:57:03 -08:00
1 parent 28efc67f5d
commit c0663537cb
1683 files changed
+220064

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
#!/usr/bin/env make
#
# 2015 makefile
#
# This work by Landon Curt Noll, Simon Cooper, and Leonid A. Broukhis
# is licensed under:
#
# Creative Commons Attribution-ShareAlike 3.0 Unported License.
#
# See: http://creativecommons.org/licenses/by-sa/3.0/
################
# tool locations
################
#
# Assume a POSIX compliant shell.
#
# On Linux
# /bin/sh = /bin/bash
#
# On NetBSD
# /bin/ksh
# /usr/pkg/bin/bash
#
# On OpenBSD
# /bin/ksh = /bin/pdksh
#
SHELL= /bin/sh
CP= cp
CPP= cpp
GUNZIP= gunzip
BUNZIP2= bunzip2
LD= ld
MAKE= make
RM= rm
SED= sed
TAR= tar
TRUE= true
MKDIR= mkdir
MV= mv
TR= tr
GREP= grep
SORT= sort
UNIQ= uniq
# Set X11_LIBDIR to the directory where the X11 library resides
#
#X11_LIBDIR= /usr/X11R6/lib
#X11_LIBDIR= /usr/X11/lib
X11_LIBDIR= /opt/X11/lib
# Set X11_INCLUDEDIR to the directory where the X11 include files reside
#
#X11_INCDIR= /usr/X11R6/include
#X11_INCDIR= /usr/X11/include
X11_INCDIR= /opt/X11/include
# Compiler warnings
#
#CWARN=
#CWARN= -Wall
#CWARN= -Wall -Wextra
CWARN= -Wall -Wextra -pedantic ${CSILENCE}
#CWARN= -Wall -Wextra -Weverything
#CWARN= -Wall -Wextra -Weverything -pedantic
#CWARN= -Wall -Wextra -Weverything -pedantic ${CSILENCE}
# Silence warnings that ${CWARN} would normally complain about
#
#CSILENCE=
CSILENCE= -Wno-sign-compare -Wno-missing-prototypes \
-Wno-padded -Wno-shadow \
-Wno-sign-conversion
# compiler standard
#
#CSTD=
#CSTD= -ansi
CSTD= -std=c99
# compiler bit architecture
#
# Some entries require 32-bitness:
# ARCH= -m32
#
# Some entries require 64-bitess:
# ARCH= -m64
#
# By default we assume nothing:
#
ARCH=
# defines that are needed to compile
#
CDEFINE=
# include files that are needed to compile
#
CINCLUDE=
# optimization
#
# Most compiles will safely use -O2. Some can use only -O1 or -O.
# A few compilers have broken optimizers or this entry make break
# under those buggy optimizers and thus you may not want anything.
# Reasonable compilers will allow for -O3.
#
#OPT=
#OPT= -O
#OPT= -O1
#OPT= -O2
OPT= -O3
# default flags for ANSI C compilation
#
CFLAGS= ${CWARN} ${CSTD} ${ARCH} ${CDEFINE} ${CINCLUDE} ${OPT}
# Libraries needed to build
#
LIBS=
# ANSI compiler
#
# Set CC to the name of your ANSI compiler.
#
# Some entries seem to need gcc. If you have gcc, set
# both CC and MAY_NEED_GCC to gcc.
#
# If you do not have gcc, set CC to the name of your ANSI compiler, and
# set MAY_NEED_GCC to either ${CC} (and hope for the best) or to just :
# to disable such programs.
#
CC= cc
#CC=clang
MAY_NEED_GCC= gcc
##############################
# Special flags for this entry
##############################
#
ENTRY= prog
CSRC= ${ENTRY}.c
OBJ= ${ENTRY}.o
DATA=
ALT_OBJ=
ALT_ENTRY=
TARGET= ${ENTRY}
#################
# build the entry
#################
#
all: ${TARGET} ${DATA}
@${TRUE}
${ENTRY}: ${CSRC}
${CC} ${CFLAGS} $< -o $@ ${LIBS}
test: makeholes prog-test.sh ${TARGET}
${SHELL} ./prog-test.sh
makeholes: makeholes.c
${CC} ${CFLAGS} $< -o $@ ${LIBS}
# alternative executable
#
alt: ${ALT_ENTRY}
@${TRUE}
# data files
#
data: ${DATA}
@${TRUE}
###############
# utility rules
###############
#
everything: all alt
clean:
${RM} -f ${OBJ} ${ALT_OBJ}
clobber: clean
${RM} -f ${TARGET} ${ALT_ENTRY}
${RM} -f *.tmp
${RM} -f makeholes makeholes.o
nuke: clobber
@${TRUE}
dist_clean: nuke
@${TRUE}
install:
@echo "Surely we are joking Dr. May!"
@${TRUE}
# backwards compatibility
#
build: all
@${TRUE}
##################
# 133t hacker rulz
##################
#
love:
@echo 'not war?'
@${TRUE}
haste:
$(MAKE) waste
@${TRUE}
waste:
@echo 'haste'
@${TRUE}
make:
@echo 'Attend a maker faire'
@${TRUE}
easter_egg:
@echo you expected to sometimes mis-understand this $${RANDOM} magic
@echo chongo '<was here>' "/\\oo/\\"
@echo Readers shall not be disallowed from not failing to be unable to not partly misunderstand this partocular final echo.
# Understand the history of the Homebrew Computer Club
# as well as the West Coast Computer Faire and
# you might be confused different. :-)
#
supernova: nuke
@-if [ -r .code_anal ]; then \
${RM} -f .code_anal_v5; \
else \
echo "planet deniers, like the IAU, are amusing"; \
fi
@echo A $@ helps ${MAKE} the elements that help form planets
@${TRUE}
deep_magic:
@-if [ -r .code_anal ]; then \
ccode_analysis --deep_magic 2ed3582ec5c094a093fea2a6bcb9f19439892873c9cc45ed1ceaafe08b7d52e1b2c7cd524be3b0b2 --FNV1a_hash_512_bit "${ENTRY}"; \
else \
echo "You are holding it wrong!"; \
fi
@${TRUE}
magic: deep_magic
@-if [ -r .code_anal ]; then \
ccode_analysis --mode 216091 --level 216193 --FNV1a_hash_512_bit "${ENTRY}"; \
else \
echo "These aren't the primes you're looking for Pauline!"; \
fi
@${TRUE}
# The IOCCC resident astronomer states
#
charon: supernova
@echo $@ is a dwarf planet
@echo dwarf is a type of planet
@echo $@ is a planet
pluto: supernova
${MAKE} charon
@echo $@ is a dwarf planet
@echo dwarf is a type of planet
@echo $@ is a planet
@echo get used to having lots of planets because a $< can ${MAKE} a lot of them
+22
View File
@@ -0,0 +1,22 @@
#!/bin/ksh
COUNT=$1; shift
CMD="$@"
N=0
SYS=0
USER=0
REAL=0
while [ $N -lt $COUNT ]; do
TIME=$( { /usr/bin/time -l $CMD >/dev/null; } 2>&1 | head -n 1 )
REAL="$REAL + $(echo $TIME | cut -d' ' -f1)"
USER="$USER + $(echo $TIME | cut -d' ' -f3)"
SYS="$SYS + $(echo $TIME | cut -d' ' -f5)"
(( N = $N + 1 ))
done
printf 'avg-real\t%.3f\n' $(echo "scale=3; ( $REAL ) / $COUNT" | bc)
printf 'avg-user\t%.3f\n' $(echo "scale=3; ( $USER ) / $COUNT" | bc)
printf 'avg-sys\t%.3f\n' $(echo "scale=3; ( $SYS ) / $COUNT" | bc)
+163
View File
@@ -0,0 +1,163 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="GENERATOR" content="mkd2html 2.1.5a DL=DISCOUNT">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<link rel="stylesheet"
type="text/css"
href="../hint.css">
<title>Most Different</title>
</head>
<body>
<h1>Most Different</h1>
<p>Anthony Howe <a href="&#109;&#x61;&#105;&#108;&#116;&#x6f;&#58;&#x61;&#x63;&#104;&#x6f;&#x77;&#101;&#64;&#115;&#x6e;&#101;&#114;&#x74;&#46;&#99;&#111;&#x6d;">&#97;&#99;&#x68;&#111;&#119;&#101;&#x40;&#x73;&#110;&#101;&#x72;&#116;&#46;&#99;&#x6f;&#x6d;</a><br>
Montreal, Quebec, Canada<br>
<a href="http://www.snert.com/">http://www.snert.com/</a><br>
Twitter: @SirWumpus</p>
<h2>Judges' comments:</h2>
<h3>To use:</h3>
<pre><code>make
./prog file1 file2
./prog -d file1 file2
</code></pre>
<h3>Try:</h3>
<pre><code>./prog prog.orig.c prog.c
make test
./prog -d ABXYEFCD.tmp ACDBECFD.tmp
./prog ABXYEFCD.tmp ACDBECFD.tmp
rm -f curds.tmp whey.tmp
cp /usr/share/man/man1/cc.1 curds.tmp
cp /usr/share/man/man1/cc.1 whey.tmp
chmod 666 whey.tmp
make makeholes
./makeholes -n 1000 whey.tmp
./prog curds.tmp whey.tmp
./avgtime.sh 100 ./prog curds.tmp whey.tmp
# Assuming curl(1) installed, grab a really HUGE text file.
curl -L -o war-and-peace.txt http://www.gutenberg.org/ebooks/2600.txt.utf-8
cp war-and-peace.txt nuked.tmp
./makeholes -c'~' -n 1000 nuked.tmp
./prog war-and-peace.txt nuked.tmp
./avgtime.sh 100 ./prog war-and-peace.txt nuked.tmp
</code></pre>
<h3>Selected Judges Remarks:</h3>
<p>This is the best use of the FNV that we have seen in the IOCCC so far!
The output, when used without -d, is compatible with POSIX diff and
is suitable for use with patch.</p>
<p>We welcome back Canada to the list of nations from where winning
entries have been submitted.</p>
<p>Is this code a bug or a feature? :-) Or is this an attempt to corrupt the
programming of our youth? Should we heed Kyle&rsquo;s mom words that she uttered
during a South Park P.T.A. Meeting?</p>
<p> &ldquo;We must stop dirty &copy; language from getting to our children&rsquo;s ears!&rdquo;</p>
<p> <a href="https://www.youtube.com/watch?v=bOR38552MJA">Blame Canada</a>:</p>
<p>Or should we teach our youth to understand the intricacies of this code?
Ying Tong Iddle I Po! We suggest you read the source for yourself, which
might be easier than the academic papers it was inspired by.</p>
<p>NOTE: Unlike the original entry source, prog.orig.c, prog.c uses a
64 bit FNV hash and fixes a function call warning.</p>
<h2>Author&rsquo;s comments:</h2>
<h2>Features</h2>
<ul>
<li><p>&ldquo;An O(NP) Sequence Comparison Algorithm&rdquo; by Wu, Manber, Myers, Miller.</p></li>
<li><p>Output compatible with patch(1).</p></li>
<li><p>Strokes one of the judge&rsquo;s ego (I couldn&rsquo;t email chocolate or curry).</p></li>
</ul>
<h2>Description</h2>
<p>This is a functioning micro diff tool using an <a href="http://myerslab.mpi-cbg.de/wp-content/uploads/2014/06/np_diff.pdf">O(NP) algorithm</a>, compared to the older <a href="http://www.xmailserver.org/diff2.pdf">O(ND) difference algorithm</a> used by some versions of diff. Its output is based on the default diff(1) output described by POSIX and <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html">The Open Group Base Specifications</a>. The output is suitable for use with patch(1).</p>
<p>The -d option simply writes the edit distance between file1 and file2.</p>
<h2>Observations</h2>
<p>The FNV1a hash is a little slow compared to the trival hash GNU Diff uses. I downloaded a plain text copy of &ldquo;War And Peace&rdquo; from Project Gutenberg, used <code>makeholes.c</code> to make 1000 random changes, then profiled and timed the program verses GNU Diff. The bottle neck appears to be in the file I/O and line hashing with an average +0.05s slower. Using a huge file like &ldquo;War And Peace&rdquo; for testing offsets the diff(1) optimised file I/O.</p>
<p>There is no hash collision checking, partly because FNV1a appears to generate very <a href="http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed">few collisions</a> and an assumption that localised collisions within a region of edits are highly unlikely.</p>
<h2>Support Files</h2>
<ul>
<li><p><code>prog-test.sh</code><br>
Basic test program verifies known test edit distances and patch support.</p></li>
<li><p><code>avgtime.sh</code></p></li>
<li><p><code>makeholes.c</code><br>
Random edits (holes) made to a file in-place.</p></li>
</ul>
<h2>References</h2>
<p>Wu, Manber, Myers, and Miller; August 1989;<br>
&ldquo;An O(NP) Sequence Comparison Algorithm&rdquo;;<br>
<a href="http://myerslab.mpi-cbg.de/wp-content/uploads/2014/06/np_diff.pdf">http://myerslab.mpi-cbg.de/wp-content/uploads/2014/06/np_diff.pdf</a></p>
<p>Fowler, Noll, Vo; 1994<br>
<a href="http://www.isthe.com/chongo/tech/comp/fnv/index.html">http://www.isthe.com/chongo/tech/comp/fnv/index.html</a></p>
<p>Fowler, Noll, Vo on Wikipedia<br>
<a href="https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function">https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function</a></p>
<p>&ldquo;diff&rdquo;, The Open Group Base Specifications Issue 7<br>
IEEE Std 1003.1, 2013 Edition<br>
<a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html">http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html</a></p>
<p>Eugene W. Myers; &ldquo;An O(ND) Difference Algorithm and Its Variations&rdquo;;<br>
Algorithmica, 1986, pages. 251-266<br>
<a href="http://www.xmailserver.org/diff2.pdf">http://www.xmailserver.org/diff2.pdf</a></p>
<p>Webb Miller and Eugene W. Myers; &ldquo;A File Comparison Program&rdquo;;<br>
Software-Practice And Experience, Vol. 15(11). 1025-1040 (November 1985)<br>
<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.189.70&amp;rep=rep1&amp;type=pdf">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.189.70&amp;rep=rep1&amp;type=pdf</a></p>
<p>D.S. Hirschberg, &ldquo;A linear space algorithm for computing maximal common subsequence problem&rdquo;;<br>
Comm. of ACM, Vol. 18, June 1975, pages 341-343<br>
<a href="http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/DynProg/Docs/Hirschberg-LCS-1975.pdf">http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/DynProg/Docs/Hirschberg-LCS-1975.pdf</a></p>
<p>Which hashing algorithm is best for uniqueness and speed?<br>
<a href="http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed">http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed</a></p>
<hr />
<!--
(c) Copyright 1984-2016, [Leo Broukhis, Simon Cooper, Landon Curt Noll][judges] - All rights reserved
This work is licensed under a [Creative Commons Attribution-ShareAlike 3.0 Unported License][cc].
[judges]: http://www.ioccc.org/judges.html
[cc]: http://creativecommons.org/licenses/by-sa/3.0/
-->
<TABLE><TR>
<TD><a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a></TD>
<TD><P>&copy; Copyright 1984-2016,
<A HREF="/judges.html">Leo Broukhis, Simon Cooper, Landon Curt Noll</A>
- All rights reserved<BR>
This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.</P></TD>
<TD>&nbsp;<!--<a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Transitional" height="31" width="88"></a>--></TD>
</TR></TABLE>
</body>
</html>
+160
View File
@@ -0,0 +1,160 @@
# Most Different
Anthony Howe <achowe@snert.com>
Montreal, Quebec, Canada
<http://www.snert.com/>
Twitter: @SirWumpus
## Judges' comments:
### To use:
make
./prog file1 file2
./prog -d file1 file2
### Try:
./prog prog.orig.c prog.c
make test
./prog -d ABXYEFCD.tmp ACDBECFD.tmp
./prog ABXYEFCD.tmp ACDBECFD.tmp
rm -f curds.tmp whey.tmp
cp /usr/share/man/man1/cc.1 curds.tmp
cp /usr/share/man/man1/cc.1 whey.tmp
chmod 666 whey.tmp
make makeholes
./makeholes -n 1000 whey.tmp
./prog curds.tmp whey.tmp
./avgtime.sh 100 ./prog curds.tmp whey.tmp
# Assuming curl(1) installed, grab a really HUGE text file.
curl -L -o war-and-peace.txt http://www.gutenberg.org/ebooks/2600.txt.utf-8
cp war-and-peace.txt nuked.tmp
./makeholes -c'~' -n 1000 nuked.tmp
./prog war-and-peace.txt nuked.tmp
./avgtime.sh 100 ./prog war-and-peace.txt nuked.tmp
### Selected Judges Remarks:
This is the best use of the FNV that we have seen in the IOCCC so far!
The output, when used without -d, is compatible with POSIX diff and
is suitable for use with patch.
We welcome back Canada to the list of nations from where winning
entries have been submitted.
Is this code a bug or a feature? :-) Or is this an attempt to corrupt the
programming of our youth? Should we heed Kyle's mom words that she uttered
during a South Park P.T.A. Meeting?
"We must stop dirty (C) language from getting to our children's ears!"
[Blame Canada](https://www.youtube.com/watch?v=bOR38552MJA):
Or should we teach our youth to understand the intricacies of this code?
Ying Tong Iddle I Po! We suggest you read the source for yourself, which
might be easier than the academic papers it was inspired by.
NOTE: Unlike the original entry source, prog.orig.c, prog.c uses a
64 bit FNV hash and fixes a function call warning.
## Author's comments:
Features
--------
* "An O(NP) Sequence Comparison Algorithm" by Wu, Manber, Myers, Miller.
* Output compatible with patch(1).
* Strokes one of the judge's ego (I couldn't email chocolate or curry).
Description
-----------
This is a functioning micro diff tool using an [O(NP) algorithm][Wu+89], compared to the older [O(ND) difference algorithm][Mye86] used by some versions of diff. Its output is based on the default diff(1) output described by POSIX and [The Open Group Base Specifications][SUSV7]. The output is suitable for use with patch(1).
The -d option simply writes the edit distance between file1 and file2.
Observations
------------
The FNV1a hash is a little slow compared to the trival hash GNU Diff uses. I downloaded a plain text copy of "War And Peace" from Project Gutenberg, used ``makeholes.c`` to make 1000 random changes, then profiled and timed the program verses GNU Diff. The bottle neck appears to be in the file I/O and line hashing with an average +0.05s slower. Using a huge file like "War And Peace" for testing offsets the diff(1) optimised file I/O.
There is no hash collision checking, partly because FNV1a appears to generate very [few collisions][HshCmp] and an assumption that localised collisions within a region of edits are highly unlikely.
Support Files
-------------
* ``prog-test.sh``
Basic test program verifies known test edit distances and patch support.
* ``avgtime.sh``
* ``makeholes.c``
Random edits (holes) made to a file in-place.
References
----------
Wu, Manber, Myers, and Miller; August 1989;
"An O(NP) Sequence Comparison Algorithm";
<http://myerslab.mpi-cbg.de/wp-content/uploads/2014/06/np_diff.pdf>
Fowler, Noll, Vo; 1994
<http://www.isthe.com/chongo/tech/comp/fnv/index.html>
Fowler, Noll, Vo on Wikipedia
<https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function>
"diff", The Open Group Base Specifications Issue 7
IEEE Std 1003.1, 2013 Edition
<http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html>
Eugene W. Myers; "An O(ND) Difference Algorithm and Its Variations";
Algorithmica, 1986, pages. 251-266
<http://www.xmailserver.org/diff2.pdf>
Webb Miller and Eugene W. Myers; "A File Comparison Program";
Software-Practice And Experience, Vol. 15(11). 1025-1040 (November 1985)
<http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.189.70&rep=rep1&type=pdf>
D.S. Hirschberg, "A linear space algorithm for computing maximal common subsequence problem";
Comm. of ACM, Vol. 18, June 1975, pages 341-343
<http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/DynProg/Docs/Hirschberg-LCS-1975.pdf>
Which hashing algorithm is best for uniqueness and speed?
<http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed>
[Wu+89]: http://myerslab.mpi-cbg.de/wp-content/uploads/2014/06/np_diff.pdf
[FNV94]: http://www.isthe.com/chongo/tech/comp/fnv/index.html
[FNVWi]: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
[Mye86]: http://www.xmailserver.org/diff2.pdf
[SUSV7]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html
[Mil85]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.189.70&rep=rep1&type=pdf
[Hir75]: http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/DynProg/Docs/Hirschberg-LCS-1975.pdf
[HshCmp]: http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed
--------------------------------------------------------------------------------
<!--
(c) Copyright 1984-2016, [Leo Broukhis, Simon Cooper, Landon Curt Noll][judges] - All rights reserved
This work is licensed under a [Creative Commons Attribution-ShareAlike 3.0 Unported License][cc].
[judges]: http://www.ioccc.org/judges.html
[cc]: http://creativecommons.org/licenses/by-sa/3.0/
-->
+101
View File
@@ -0,0 +1,101 @@
/*
* makeholes.c
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
static unsigned char hole = '@';
static unsigned long count = 100;
static const char usage[] =
"usage: makeholes [-b value][-c char][-n count] file ...\n";
int
offcmp(const void *a, const void *b)
{
return *(off_t *)a - *(off_t *)b;
}
void
process(const char *file)
{
ssize_t x;
int fd, rd;
size_t size;
struct stat sb;
unsigned long n;
off_t mask, *seeks;
if (stat(file, &sb) != 0)
return;
if ((fd = open(file, O_WRONLY)) < 0)
return;
if ((rd = open("/dev/urandom", O_RDONLY)) < 0)
goto error1;
size = count * sizeof (*seeks);
if ((seeks = malloc(size)) == NULL)
goto error2;
for (x = 0; x < size; )
x += read(rd, seeks+x, size-x);
mask = (off_t)(~0UL >> 1);
for (n = 0; n < count; n++) {
seeks[n] &= mask;
seeks[n] %= sb.st_size;
}
qsort(seeks, count, sizeof (*seeks), offcmp);
for (n = 0; n < count; n++) {
if (lseek(fd, seeks[n], SEEK_SET) < 0)
break;
if (write(fd, &hole, sizeof (hole)) != sizeof (hole))
break;
}
free(seeks);
error2:
(void) close(rd);
error1:
(void) close(fd);
}
int
main(int argc, char **argv)
{
int ch, argi;
while ((ch = getopt(argc, argv, "b:c:n:")) != -1) {
switch (ch) {
case 'b':
hole = (unsigned char) strtoul(optarg, NULL, 0);
break;
case 'c':
hole = (unsigned char) *optarg;
break;
case 'n':
count = strtoul(optarg, NULL, 10);
break;
default:
optind = argc;
break;
}
}
if (argc <= optind) {
(void) fprintf(stderr, usage);
return EXIT_FAILURE;
}
for (argi = optind; argi < argc; argi++)
process(argv[argi]);
return EXIT_SUCCESS;
}
+132
View File
@@ -0,0 +1,132 @@
#!/bin/ksh
# Assume a POSIX compliant shell.
PROG="./prog"
args=$(getopt 'f:w' $*)
if [ $? -ne 0 ]; then
echo "usage: prog-test.sh [-w][-f flags]"
exit 2
fi
set -- $args
while [ $# -gt 0 ]; do
case "$1" in
-w)
PROG="./prog-w64"
;;
-f)
flags=$2; shift
;;
--)
shift; break
;;
esac
shift
done
function distance
{
typeset A="$1"; shift
typeset B="$1"; shift
typeset expect="$1"; shift
printf "$A" | sed -e 's/./&\
/g' >$A.tmp
printf "$B" | sed -e 's/./&\
/g' >$B.tmp
echo "<<< A='$A' B='$B' $@"
typeset dist=$($PROG -d $@ $A.tmp $B.tmp | tr -d '\r')
printf '>>> got=%d expect=%d ' "$dist" "$expect"
if [ "$dist" -ne "$expect" ]; then
echo FAIL
return 1
fi
echo -OK-
return 0
}
function dif
{
typeset A="$1"; shift
typeset B="$1"; shift
typeset expect="$1"; shift
echo "==== $A $B"
$PROG $A $B | tee patch.tmp
typeset ex=$?
if [ "$expect" -eq 0 ]; then
printf "got=%d expect=%d " $ex $expect
if [ $expect -ne $ex ]; then
echo FAIL
return 1
fi
echo -OK-
return 0
fi
printf "forward patch "
cp $A copy.tmp
if ! patch -f -s copy.tmp patch.tmp ; then
echo FAIL
return 1
fi
echo -OK-
printf "forward compare "
if ! cmp $B copy.tmp ; then
echo FAIL
return 1
fi
echo -OK-
printf "reverse patch "
if ! patch -R -f -s copy.tmp patch.tmp ; then
echo FAIL
return 1
fi
echo -OK-
printf "reverse compare "
if ! cmp $A copy.tmp ; then
echo FAIL
return 1
fi
echo -OK-
return 0
}
distance "1" "1" 0 $flags
distance "1" "A" 2 $flags
distance "123" "ABCDE" 8 $flags
distance "ABCDE" "123" 8 $flags
distance "ABD" "ABCD" 1 $flags
distance "ABCD" "ABD" 1 $flags
distance "ABCD" "ACDBECFD" 4 $flags
distance "ABCDEF" "ABXYEFCD" 6 $flags
distance "ABCDEFGHIJK" "ABCEFGIJKDEFGHIJK" 6 $flags
distance "ABCABBA" "CBABAC" 5 $flags
distance "ACEBDABBABED" "ACBDEACBED" 6 $flags
touch EMPTY.tmp
dif 1.tmp 1.tmp 0
dif EMPTY.tmp 123.tmp 1
dif 123.tmp EMPTY.tmp 1
dif ABCD.tmp ACDBECFD.tmp 1
dif ACDBECFD.tmp ABCD.tmp 1
dif 123.tmp ABCDE.tmp 1
dif ABCDE.tmp 123.tmp 1
# Note that prog and diff(1) have same edit distance,
# but differ in the output.
dif CBABAC.tmp ABCABBA.tmp 1
dif ABCABBA.tmp CBABAC.tmp 1
rm copy.tmp* 2>/dev/null
echo DONE
+242
View File
@@ -0,0 +1,242 @@
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
typedef struct e {
int op; int x; int y; long a; long b; struct e *n;
} E;
typedef struct {
int y;
E *e;
} X;
typedef struct {
long q;
unsigned long long y;
} h;
typedef struct {
unsigned long z;
unsigned long j;
h b[1];
} H;
int I;
int P;
H *A, *B;
FILE *f, *g;
X *Q, *q;
H *
N(H *O)
{
unsigned long z;
H *Y;
z = O ? O->z << 1 : 65536;
if (!(Y = realloc(O, sizeof (*O) + z * sizeof (O->b))))
err(2, 0);
Y->z = z;
if (!O)
Y->j = 0;
return Y;
}
H *
F(FILE *Q)
{
unsigned long long h;
H *y;
long L, o, n;
unsigned char buf[65536], *b;
y = N(0);
L = 1;
o = 0;
h = 14695981039346656037ULL;
y->b[L].q = o;
while (0 < (n = fread(buf, 1, sizeof (buf), Q))) {
b = buf;
while (0 < n--) {
h ^= *b;
h += (h<<1) + (h<<4) + (h<<5) + (h<<7) + (h<<8) + (h<<40);
o++;
if (*b++ == '\n') {
y->b[L++].y = h;
if (y->z <= L)
y = N(y);
y->b[L].q = o;
h = 14695981039346656037ULL;
}
}
}
y->j = L-1;
rewind(Q);
return y;
}
FILE *
O(char *u)
{
int i;
FILE *Q;
if (!(Q = fopen(u, "r")) && !strcmp("-", u)) {
if ((Q = tmpfile())) {
while ((i = getchar()) != EOF)
fputc(i, Q);
rewind(Q);
}
}
if (!Q) err(2, "%s", u);
return Q;
}
void
W(FILE *Q)
{
int i;
while ((i = fgetc(Q)) != EOF) {
putchar(i);
if (i == '\n')
break;
}
}
E *
R(E *K)
{
E *a, *b;
b = 0;
while (K) {
a = K->n;
K->n = b;
b = K;
K = a;
}
return b;
}
void
D(E *K)
{
E *a, *b;
for (K = R(K); K; ) {
b = K;
if (K->op) {
do {
a = b;
b = b->n;
} while (b && b->op && a->y+1 == b->y);
if (K->y < a->y)
printf("%da%d,%d\n", K->x, K->y, a->y);
else
printf("%da%d\n", K->x, K->y);
fseek(g, K->b, SEEK_SET);
for ( ; K != b; K = K->n) {
printf("> ");
W(g);
}
} else {
do {
a = b;
b = b->n;
} while (b && !b->op && a->x+1 == b->x);
if (K->x < a->x)
printf("%d,%dd%d\n", K->x, a->x, K->y);
else
printf("%dd%d\n", K->x, K->y);
fseek(f, K->a, SEEK_SET);
for ( ; K != b; K = K->n) {
printf("< ");
W(f);
}
}
}
}
void
K(int k)
{
X h = Q[k-1];
X v = Q[k+1];
int x, y, op;
E *p;
if (v.y < h.y+1) {
op = 1;
y = h.y+1;
p = h.e;
} else {
op = 0;
y = v.y;
p = v.e;
}
x = y - k;
if (0 < y || 0 < x) {
E *e = malloc(sizeof (*e));
e->x = x;
e->y = y;
e->n = p;
e->op = op ^ I;
e->a = A->b[x].q;
e->b = B->b[y].q;
if (I) {
long c = e->a;
e->a = e->b;
e->b = c;
e->x = y;
e->y = x;
}
Q[k].e = e;
}
while (x < A->j && y < B->j && A->b[x+1].y == B->b[y+1].y) {
x++;
y++;
}
Q[k].y = y;
}
int
T(void)
{
int k, p, d;
if (A->j > B->j) {
void *t = A;
A = B;
B = t;
I = 1;
}
d = B->j - A->j;
if (!(q = calloc(A->j + B->j + 3, sizeof (*Q))))
err(2, 0);
for (k = 0; k < A->j + B->j + 3; k++)
q[k].y = -1;
Q = q + A->j + 1;
p = -1;
do {
p++;
for (k = -p; k < d; k++) {
K(k);
}
for (k = d + p; d <= k; k--) {
K(k);
}
} while (Q[d].y != B->j);
if (!P)
D(Q[d].e);
free(q);
return d + 2 * p;
}
int
main(int x, char **y)
{
int i;
while ((i = getopt(x, y, "d")) != -1) {
switch (i) {
case 'd':
P = 1;
break;
default:
optind = x;
break;
}
}
if (x <= optind)
errx(2, "usage: %s [-d] file1 file2", *y);
f = O(y[optind]);
g = O(y[optind+1]);
if (!(A = F(f)))
err(2, "%s", y[optind]);
if (!(B = F(g)))
err(2, "%s", y[optind+1]);
i = T();
if (P) printf("%d\n", i);
return 0 < i;
}
+242
View File
@@ -0,0 +1,242 @@
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
typedef struct e {
int op; int x; int y; long a; long b; struct e *n;
} E;
typedef struct {
int y;
E *e;
} X;
typedef struct {
long q;
unsigned long y;
} h;
typedef struct {
unsigned long z;
unsigned long j;
h b[1];
} H;
int I;
int P;
H *A, *B;
FILE *f, *g;
X *Q, *q;
H *
N(H *O)
{
unsigned long z;
H *Y;
z = O ? O->z << 1 : 65536;
if (!(Y = realloc(O, sizeof (*O) + z * sizeof (O->b))))
err(2, 0);
Y->z = z;
if (!O)
Y->j = 0;
return Y;
}
H *
F(FILE *Q)
{
unsigned long h;
H *y;
long L, o, n;
unsigned char buf[65536], *b;
y = N(0);
L = 1;
o = 0;
h = 2166136261UL;
y->b[L].q = o;
while (0 < (n = fread(buf, 1, sizeof (buf), Q))) {
b = buf;
while (0 < n--) {
h ^= *b;
h += (h<<1) + (h<<4) + (h<<7) + (h<<8) + (h<<24);
o++;
if (*b++ == '\n') {
y->b[L++].y = h;
if (y->z <= L)
y = N(y);
y->b[L].q = o;
h = 2166136261UL;
}
}
}
y->j = L-1;
rewind(Q);
return y;
}
FILE *
O(char *u)
{
int i;
FILE *Q;
if (!(Q = fopen(u, "r")) && !strcmp("-", u)) {
if ((Q = tmpfile())) {
while ((i = getchar()) != EOF)
fputc(i, Q);
rewind(Q);
}
}
if (!Q) err(2, "%s", u);
return Q;
}
void
W(FILE *Q)
{
int i;
while ((i = fgetc(Q)) != EOF) {
putchar(i);
if (i == '\n')
break;
}
}
E *
R(E *K)
{
E *a, *b;
b = 0;
while (K) {
a = K->n;
K->n = b;
b = K;
K = a;
}
return b;
}
void
D(E *K)
{
E *a, *b;
for (K = R(K); K; ) {
b = K;
if (K->op) {
do {
a = b;
b = b->n;
} while (b && b->op && a->y+1 == b->y);
if (K->y < a->y)
printf("%da%d,%d\n", K->x, K->y, a->y);
else
printf("%da%d\n", K->x, K->y);
fseek(g, K->b, SEEK_SET);
for ( ; K != b; K = K->n) {
printf("> ");
W(g);
}
} else {
do {
a = b;
b = b->n;
} while (b && !b->op && a->x+1 == b->x);
if (K->x < a->x)
printf("%d,%dd%d\n", K->x, a->x, K->y);
else
printf("%dd%d\n", K->x, K->y);
fseek(f, K->a, SEEK_SET);
for ( ; K != b; K = K->n) {
printf("< ");
W(f);
}
}
}
}
void
K(int k)
{
X h = Q[k-1];
X v = Q[k+1];
int x, y, op;
E *p;
if (v.y < h.y+1) {
op = 1;
y = h.y+1;
p = h.e;
} else {
op = 0;
y = v.y;
p = v.e;
}
x = y - k;
if (0 < y || 0 < x) {
E *e = malloc(sizeof (*e));
e->x = x;
e->y = y;
e->n = p;
e->op = op ^ I;
e->a = A->b[x].q;
e->b = B->b[y].q;
if (I) {
long c = e->a;
e->a = e->b;
e->b = c;
e->x = y;
e->y = x;
}
Q[k].e = e;
}
while (x < A->j && y < B->j && A->b[x+1].y == B->b[y+1].y) {
x++;
y++;
}
Q[k].y = y;
}
int
T()
{
int k, p, d;
if (A->j > B->j) {
void *t = A;
A = B;
B = t;
I = 1;
}
d = B->j - A->j;
if (!(q = calloc(A->j + B->j + 3, sizeof (*Q))))
err(2, 0);
for (k = 0; k < A->j + B->j + 3; k++)
q[k].y = -1;
Q = q + A->j + 1;
p = -1;
do {
p++;
for (k = -p; k < d; k++) {
K(k);
}
for (k = d + p; d <= k; k--) {
K(k);
}
} while (Q[d].y != B->j);
if (!P)
D(Q[d].e);
free(q);
return d + 2 * p;
}
int
main(int x, char **y)
{
int i;
while ((i = getopt(x, y, "d")) != -1) {
switch (i) {
case 'd':
P = 1;
break;
default:
optind = x;
break;
}
}
if (x <= optind)
errx(2, "usage: %s [-d] file1 file2", *y);
f = O(y[optind]);
g = O(y[optind+1]);
if (!(A = F(f)))
err(2, "%s", y[optind]);
if (!(B = F(g)))
err(2, "%s", y[optind+1]);
i = T(f, g, A, B);
if (P) printf("%d\n", i);
return 0 < i;
}
+69
View File
@@ -0,0 +1,69 @@
.POSIX :
.SUFFIXES :
A = .a
O = .o
.SUFFIXES : .c .h .i $O $A
########################################################################
### No further configuration beyond this point.
########################################################################
top_srcdir := ..
CC := gcc
CFLAGS := -g -O2 -std=c99 -Wall -pedantic -Wno-char-subscripts
LDFLAGS :=
# Assume a POSIX compliant shell.
#
# On Linux
# /bin/sh = /bin/bash
#
# On NetBSD
# /bin/ksh
# /usr/pkg/bin/bash
#
# On OpenBSD
# /bin/ksh = /bin/pdksh
#
SHELL := /bin/ksh
W64CC := i686-w64-mingw32-gcc
W64CFLAGS := -I. -Os -s -std=c99 -Wno-char-subscripts
ZIP := README.txt prog-w64.exe prog-test.sh avgtime.sh makeholes-w64.exe
.c$O :
${CC} ${CFLAGS} -c $<
.c$E :
$(CC) $(CFLAGS) $(LDFLAGS) -o$* $<
$O :
$(LD) $(LDFLAGS) -o$* $*$O
.c.i:
${CC} -E ${CFLAGS} $*.c >$*.i
########################################################################
all: build
build: prog
clean:
-rm prog *.exe *.i *$O *.tmp *.rej *.orig *.core *.out 2>/dev/null
distclean: clean
prog: prog.c
${CC} ${CFLAGS} ${LDFLAGS} -o$@ prog.c
prog-w64: err.h prog.c
${W64CC} ${W64CFLAGS} ${LDFLAGS} -o$@ prog.c
test:
${SHELL} ${top_srcdir}/prog-test.sh
test-w64:
${SHELL} ${top_srcdir}/prog-test.sh -w
+46
View File
@@ -0,0 +1,46 @@
/*
* Trival err.h
*/
#ifndef __err_h__
#define __err_h__
#ifdef __cplusplus
extern "C" {
#endif
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#define warnx(...) { fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); }
#define warn(...) { \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, ": %s\n", strerror(errno)); \
}
#define vwarnx(fmt, args) { vfprintf(stderr, fmt, args); fputc('\n', stderr); }
#define vwarn(fmt, args) { \
vfprintf(stderr, fmt, args); \
fprintf(stderr, "%s%s\n", (fmt) ? ": " : "", strerror(errno)); \
}
#define errx(ex, ...) { fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); exit(ex); }
#define err(ex, ...) { \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, ": %s\n", strerror(errno)); \
exit(ex); \
}
#define verrx(ex, fmt, args) { vfprintf(stderr, fmt, args); fputc('\n', stderr); exit(ex); }
#define verr(ex, fmt, args) { \
vfprintf(stderr, fmt, args); \
fprintf(stderr, "%s%s\n", (fmt) ? ": " : "", strerror(errno)); \
exit(ex); \
}
#ifdef __cplusplus
}
#endif
#endif /* __err_h__ */
+448
View File
@@ -0,0 +1,448 @@
/*
* npdif.c
*
* Wu, Manber, Myers, Miller; August 1989;
* "An O(NP) Sequence Comparison Algorithm"
*
* Public Domain 2015 by Anthony Howe. No warranty.
*
* Synopsis: npdif <file1> <file2>
*
* Exit Status
* 0 no difference
* 1 difference
* 2 error
*/
#define FAST
#define FNV64
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#ifndef INIT_SIZE
#define INIT_SIZE 8196 /* Power of two. */
#endif
/**
* FNV1a
*
* https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
* http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed
* http://www.isthe.com/chongo/tech/comp/fnv/index.html
*
* Hash Size Prime Offset
* 32-bit 16777619 0x01000193 2166136261 0x811C9DC5
* 64-bit 1099511628211 0x100000001b3 14695981039346656037 0xCBF29CE34244AD25
*/
#ifdef FNV64
#define FNV_INIT 14695981039346656037ULL
#define FNV_PRIME 1099511628211ULL
typedef unsigned long long Hash;
#else /* FNV64 */
#define FNV_INIT 2166136261UL
#define FNV_PRIME 16777619UL
typedef unsigned long Hash;
#endif /* FNV64 */
typedef struct edit {
int op; /* 1 = insert, 0 = delete */
int x; /* Index into A. */
int y; /* Index into B. */
long a; /* seek into A */
long b; /* seek into B */
struct edit *next;
} Edit;
typedef struct {
int y;
Edit *edit;
} Vertex;
typedef struct {
long seek;
Hash hash;
} HashLine;
typedef struct {
size_t size;
size_t length;
HashLine base[1];
} HashArray;
static int debug;
static int invert;
static int print_distance;
static HashArray *A, *B;
static FILE *fpA, *fpB;
static Vertex *fp, *fp_base;
#define EXIT_ERROR 2
#define INFO(...) { if (0 < debug) warnx(__VA_ARGS__); }
#define DEBUG(...) { if (1 < debug) warnx(__VA_ARGS__); }
#define DUMP(...) { if (2 < debug) warnx(__VA_ARGS__); }
/*
* Expand hash table.
*/
HashArray *
hash_expand(HashArray *orig)
{
size_t size;
HashArray *copy;
/* Size does not account for the initial base element.
* So you have 0 < size with a sentinel or 1 <= size.
*/
size = orig != NULL ? orig->size << 1 : INIT_SIZE;
if (NULL == (copy = realloc(orig, sizeof (*orig) + size * sizeof (orig->base))))
err(EXIT_ERROR, NULL);
copy->size = size;
if (orig == NULL)
copy->length = 0;
return copy;
}
/*
* @param fp
* File to scan and hash by line.
*
* @return
* Pointer to an 1-based array of hashed lines.
*/
HashArray *
hash_file(FILE *fp)
{
Hash h;
HashArray *hash;
long lineno, offset, n;
unsigned char buf[INIT_SIZE], *b;
hash = hash_expand(NULL);
/* Assume 1-base array. */
lineno = 1;
offset = 0;
h = FNV_INIT;
hash->base[lineno].seek = offset;
while (0 < (n = fread(buf, 1, sizeof (buf), fp))) {
b = buf;
while (0 < n--) {
h ^= *b;
#ifdef FAST
#ifdef FNV64
/* 0x100000001b3 */
h += (h<<1) + (h<<4) + (h<<5) + (h<<7) + (h<<8) + (h<<40);
#else /* FNV64 */
/* 0x01000193 */
h += (h<<1) + (h<<4) + (h<<7) + (h<<8) + (h<<24);
#endif /* FNV64 */
#else /* FAST */
h *= FNV_PRIME;
#endif /* FAST */
offset++;
if (*b++ == '\n') {
hash->base[lineno++].hash = h;
if (hash->size <= lineno)
hash = hash_expand(hash);
hash->base[lineno].seek = offset;
h = FNV_INIT;
}
}
}
/* Correct the length, base[1..length] inclusive. */
hash->length = lineno-1;
rewind(fp);
return hash;
}
/*
* Open file.
*
* If filename is the standard input filename -, copy
* standard input to a temporary file. Return pointer
* to the temporary file open for reading.
*
* If filename is some other filename then return a
* pointer to a file stream ready for reading.
*
* Any errors, write error message and return NULL.
*/
FILE *
file(char *u)
{
int i;
FILE *fp;
if (NULL == (fp = fopen(u, "r")) && 0 == strcmp("-", u)) {
if ((fp = tmpfile()) != NULL) {
while ((i = getchar()) != EOF)
(void) fputc(i, fp);
rewind(fp);
}
}
if (NULL == fp) err(EXIT_ERROR, "%s", u);
return fp;
}
void
echoline(FILE *fp)
{
int ch;
while ((ch = fgetc(fp)) != EOF) {
(void) putchar(ch);
if (ch == '\n')
break;
}
}
Edit *
reverse_script(Edit *curr)
{
Edit *a, *b;
b = NULL;
while (curr != NULL) {
a = curr->next;
curr->next = b;
b = curr;
curr = a;
}
return b;
}
void
dump_script(Edit *curr)
{
Edit *a, *b;
for (curr = reverse_script(curr); curr != NULL; ) {
b = curr;
if (curr->op) {
do {
a = b;
DEBUG("curr.x=%d curr.y=%d a.x=%d a.y=%d b.x=%d b.y=%d", curr->x, curr->y, a->x, a->y, b->x, b->y);
b = b->next;
} while (b != NULL && b->op && a->y+1 == b->y);
if (curr->y < a->y)
(void) printf("%da%d,%d\n", curr->x, curr->y, a->y);
else
(void) printf("%da%d\n", curr->x, curr->y);
(void) fseek(fpB, curr->b, SEEK_SET);
for ( ; curr != b; curr = curr->next) {
(void) printf("> ");
echoline(fpB);
}
} else {
do {
a = b;
DEBUG("curr.x=%d curr.y=%d a.x=%d a.y=%d b.x=%d b.y=%d", curr->x, curr->y, a->x, a->y, b->x, b->y);
b = b->next;
} while (b != NULL && !b->op && a->x+1 == b->x);
if (curr->x < a->x)
(void) printf("%d,%dd%d\n", curr->x, a->x, curr->y);
else
(void) printf("%dd%d\n", curr->x, curr->y);
(void) fseek(fpA, curr->a, SEEK_SET);
for ( ; curr != b; curr = curr->next) {
(void) printf("< ");
echoline(fpA);
}
}
}
}
void
snake(int k)
{
/* fp[] holds the furthest y along diagonal k. */
Vertex h = fp[k-1];
Vertex v = fp[k+1];
/* max(fp[k-1] + 1, fp[k+1]) */
int x, y, op;
Edit *prev;
if (v.y < h.y+1) {
op = 1;
y = h.y+1;
prev = h.edit;
} else {
op = 0;
y = v.y;
prev = v.edit;
}
/* Diagonal k = y - x of matrix [-(M+1), (N-1)], where
* row 0 and column 0 are initialised with sentenial -1.
*
* k-diagonal = A and B match
* y-horizontal = insert from B
* x-vertical = delete from A
*/
x = y - k;
DUMP("snake in k=%d y=%d x=%d", k, y, x);
if (0 < y || 0 < x) {
Edit *edit = malloc(sizeof (*edit));
edit->x = x;
edit->y = y;
edit->next = prev;
edit->op = op ^ invert;
edit->a = A->base[x].seek;
edit->b = B->base[y].seek;
if (invert) {
/* Swap seek offset to match the open files. */
long c = edit->a;
edit->a = edit->b;
edit->b = c;
/* Likewise swap line numbers to match seeks. */
edit->x = y;
edit->y = x;
}
fp[k].edit = edit;
DUMP("edit op=%d x=%d y=%d", edit->op, edit->x, edit->y);
}
/* The algorithm assumes 1-based indexing, A[1..M] and B[1..N].
* NOTE no hash collision checking yet.
*/
while (x < A->length && y < B->length && A->base[x+1].hash == B->base[y+1].hash) {
x++;
y++;
}
fp[k].y = y;
DUMP("snake out k=%d y=%d x=%d", k, y, x);
}
int
edit_distance(void)
{
int k, p, delta;
/* Swap A and B if N < M. The edit distance will be the
* same, but edit script operations will be reversed.
*/
if (A->length > B->length) {
void *tmp = A;
A = B;
B = tmp;
invert = 1;
DEBUG("swap A & B");
}
/* delta = N - M where A[1..M], B[1..N], and N >= M. */
delta = B->length - A->length;
/* From -(M+1).. 0 .. (N+1); up & lower sentinels and zero. */
if (NULL == (fp_base = calloc(A->length + B->length + 3, sizeof (*fp))))
err(EXIT_ERROR, NULL);
/* fp[-(M+1)..(N+1)] := -1 */
for (k = 0; k < A->length + B->length + 3; k++)
fp_base[k].y = -1;
/* Shift origin to (M+1). */
fp = fp_base + A->length + 1;
DEBUG("delta=%d M=%lu N=%lu fp.len=%lu", delta, A->length, B->length, (A->length + B->length + 3));
p = -1;
do {
p++;
for (k = -p; k < delta; k++) {
snake(k);
DEBUG("1st fp[%d]=%d p=%d ", k, fp[k].y, p);
}
for (k = delta + p; delta <= k; k--) {
snake(k);
DEBUG("2nd fp[%d]=%d p=%d ", k, fp[k].y, p);
}
} while (fp[delta].y != B->length);
if (!print_distance)
dump_script(fp[delta].edit);
free(fp_base);
DEBUG("dist=%d delta=%d p=%d M=%lu N=%lu ", (delta < 0 ? -delta : delta) + 2 * p, delta, p, A->length, B->length);
return delta + 2 * p;
}
int
main(int argc, char **argv)
{
int ch;
while ((ch = getopt(argc, argv, "dv")) != -1) {
switch (ch) {
case 'd':
print_distance = 1;
break;
#ifndef NDEBUG
case 'v':
debug++;
break;
#endif /* NDEBUG */
default:
optind = argc;
break;
}
}
if (argc <= optind)
errx(EXIT_ERROR, "usage: %s [-d] file1 file2", argv[0]);
fpA = file(argv[optind]);
fpB = file(argv[optind+1]);
if (NULL == (A = hash_file(fpA)))
err(EXIT_ERROR, "%s", argv[optind]);
if (NULL == (B = hash_file(fpB)))
err(EXIT_ERROR, "%s", argv[optind+1]);
ch = edit_distance();
if (print_distance) printf("%d\n", ch);
#ifndef NDEBUG
free(A);
free(B);
if (ferror(fpA))
err(EXIT_ERROR, "%s", argv[optind]);
fclose(fpA);
if (ferror(fpB))
err(EXIT_ERROR, "%s", argv[optind+1]);
fclose(fpB);
#endif /* NDEBUG */
return 0 < ch;
}