#!/usr/bin/perl open STDOUT, "|sqlite3" or die "Cannot fork sqlite"; print " create table number(x integer, y1 integer, y2 integer, n integer, primary key (x,y1)); create table symbol(x integer, y integer, sym text, primary key (x,y)); create view adjacent as select number.n, number.x as nx, number.y1 as ny, symbol.sym, symbol.x as sx, symbol.y as sy from symbol, number where symbol.x between number.x - 1 and number.x + 1 and y >= y1-1 and y < y2+1 ; begin; "; while(<>) { print "insert into number values ($., $-[0], $+[0], $&);\n" while /\d+/g; print "insert into symbol values ($., $-[0], '$&');\n" while /[^.0-9\n]/g; } print "commit;\n"; print "select sum(n) from number where (x, y1) in (SELECT nx, ny from adjacent);"; print "select sum(a.n * b.n) from adjacent a, adjacent b where a.sym = '*' and a.sx = b.sx and a.sy = b.sy and (a.nx < b.nx or a.nx = b.nx and a.ny < b.ny);";