I'm both learning to use the JPDA on Netbeans and solving the Prime Generator problem of Sphere's Online Judge.
I've been reading this tutorial on netbeans.org about he JPDA, but haven't found it of much help.
This code, which is based on a Sieve of Eratostenes implementation provided by starblue here, is running like this:
2
1 10
//here the primes between 1 and 10 should print
3 5
//here the primes between 3 and 5 should print
package sphere;
/**
*
* #author Administrator
*/
//import java.util.ArrayList;
import java.util.BitSet;
import java.lang.Math.*;
import java.util.ArrayList;
public class Main
{
public static int ApproximateNthPrime(int nn)
{
double n = (double)nn;
double p;
if (nn >= 7022)
{
p = n * Math.log(n) + n * (Math.log(Math.log(n)) - 0.9385);
}
else if (nn >= 6)
{
p = n * Math.log(n) + n * Math.log(Math.log(n));
}
else if (nn > 0)
{
p = new int[] { 2, 3, 5, 7, 11 }[nn - 1];
}
else
{
p = 0;
}
return (int)p;
}
// Find all primes up to and including the limit
public static BitSet SieveOfEratosthenes(int limit)
{
final BitSet primes = new BitSet();
primes.set(0,false);
primes.set(1,false);
primes.set(2,limit,true);
for (int i =0; i*i<limit;i++)
{
if (primes.get(i))
{
for (int j=i*1; j<limit;j+=1)
{
primes.clear(j);// hace que el indice j sea false (no primo)
}
}
}
return primes;
}
public static ArrayList<Integer> GeneratePrimesSieveOfEratosthenes(int n)
{
int limit = ApproximateNthPrime(n);
BitSet bits = SieveOfEratosthenes(limit);
ArrayList <Integer> primes = new ArrayList<Integer>();
for (int i = 0, found = 0; i < limit && found < n; i++)
{
if (bits.get(i))
{
primes.add(i);
found++;
}
}
return primes;
}
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
s= r.readLine();
int test_cases = Integer.parseInt(s);
int case_counter =0;
while (case_counter<test_cases) {
// System.out.println(s);
s = r.readLine();
String [] splitted = s.split(" ");
int lower_bound = Integer.parseInt(splitted[0]);
int upper_bound = Integer.parseInt(splitted[1]);
ArrayList <Integer> primesList= GeneratePrimesSieveOfEratosthenes(upper_bound);
for (int i =0; i<primesList.size();i++){
if (primesList.get(i)<=lower_bound)System.out.println(primesList.get(i));
}
case_counter++;
System.out.println(" "); // space that separates test cases
}
}
}
I know that the ArrayList primesList isn't getting initialized and I'm suspicious of this bit of code, cause honestly, I don't quite understand it:
if (primes.get(i))
{
for (int j=i*1; j<limit;j+=1)
{
primes.clear(j);
}
}
It occurred to me to use a conditional breakpoint here with the condition of:
primes.get(j)==false
But I'm not sure if I'm able to get meaningful info this way. These are the screens I'm getting:
alt text http://img525.imageshack.us/img525/6238/breakpoints.jpg
alt text http://img98.imageshack.us/img98/5262/watchesz.jpg
I don't know how to get useful info out of this.
My questions are:
a)I want to watch the primes BitSet as its going through this loop.
How do I do that?
b) What's exactly wrong with this code?
How did you spot it using the debugger?
Please, mention the step-by-step process.
So, I extracted out the following method:
private static void printPrimes(int lower_bound, int upper_bound) {
ArrayList<Integer> primesList = GeneratePrimesSieveOfEratosthenes(upper_bound);
for (int i = 0; i < primesList.size(); i++) {
if (primesList.get(i) <= lower_bound)
System.out.println(primesList.get(i));
}
}
and changed the main() method to just call that with a couple of arbitrary arguments (10 and 100), because I didn't want to mess around with the console and the debugger at the same time. I then (I'm using Eclipse) put ordinary breakpoints at the beginning and end lines of ApproximateNthPrime(), SieveOfEratosthenes() and GeneratePrimesSieveOfEratosthenes() to make sure they were being called. (By the way, Java convention, unlike C#, is for method names to start with a lower-case letter.)
All that was without bothering to understand the code. :) However, after the first run-through, it was pretty clear that the problem is that the BitSet produced by SieveOfEratosthenes() is always empty (or rather, always entirely false). I haven't used the NetBeans debugger, but I suspect the "Local Variables" tab is your friend here.
I'm not going to do your homework for you. :) But the idea of the Sieve of Eratosthenes is to skip the prime numbers and only eliminate the non-primes. Examine your SieveOfEratosthenes() method and ask yourself: when will it skip a number?
Related
This question already has answers here:
Scramble each digit of the int a and print out the biggest possible integer
(4 answers)
Closed 2 years ago.
For example, if someone inserts 34603, the output would be 64330. I've started this problem already but I can not think of a solution that works. Also, since this is an assignment, my instructor told me that arrays are not allowed. Here is what I have thus far:
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int asl = as.length();
while(index<asl){
String num1 = as.substring(index);
String num2 = as.substring((index+1));
int con1 = Integer.parseInt(num1);
int con2 = Integer.parseInt(num2);
if(con1<con2){
System.out.println("con2: "+con2);
}
if(con1>con2){
System.out.println("con1: "+con1);
}
System.out.println("added: "+con1+" "+con2);
index++;
}
}
public static void main(String []args){
loops x = new loops();
x.biggest(4583);
}
}
I would appreciate any and all help/hints, for I am truly lost on this one.
It should be reasonably obvious that the largest possible result is obtained by arranging the digits in descending order. One of the easier and more efficient ways of doing that would be with a counting sort, but the usual forms of that involve using arrays or array-equivalents to accumulate the counts.
So standard Counting Sort is out, along with all standard sort routines aimed at rearranging sequences of items. But you can still take your inspiration from Counting Sort. For example, figure out how many 9 digits are in the input, and form a number from that many 9s. Then figure out how many 8s and append them. Then how many 7s, etc. "Appending" digits to a number can be done arithmetically, so the whole procedure can be done without an array or array equivalent, even if we consider Strings to be array equivalents (as we should).
Details are left as the exercise they are intended to be.
I won't answer the question directly for you but suggest some ideas to help you.
you need to sort the integers in place - ie no arrays/no lists.. just iterate over the integer as a string which you're doing correctly, and progressively swap values so that you end up with a sorted numerical value.
thinking of various sort algorithms, quicksort, mergesort, bubble sort, etc. you effectively pick one of these algorithms and try to implement it.
start with the basic examples for integers to sort and iteratively develop your code to successively generate the correct answer... as test cases try:
no number at all... null
then the empty string ""
then a single digit, so a number 0-9
Next two digits both in order, then out of the sort order
then 3 digits in/out of order
Once you've implemented for 3 digits you should be able to generate your solution for any number of digits.
Note: if you use Integer as the input data type, you will be limited to being able to take a maximum integer value of Integer.MAX_VALUE (which isn't that large). Try to treat the input argument as a String and the individual digits as integers for the comparison (which you are already doing), this way you'll be able to process a much larger input.
import java.util.ArrayList;
import java.util.Collections;
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int index2=1;
int asl = as.length();
ArrayList<Integer> lista = new ArrayList<Integer>();
while(index<asl){
String num1 = as.substring(index,index2);
int con1 = Integer.parseInt(num1);
lista.add(con1);
index++;
index2++;
}
//order list
Collections.sort(lista);
Collections.reverse(lista);
System.out.println(lista);
//concatenate numbers
}
public static void main(String []args){
loops x = new loops();
x.biggest(34603);
}
}
**anything consult back. **
Ok, I came up with this. It's not the prettiest solution, I recognize that, but it DOES work. Have a look:
public class loops{
public int a,b,c,d,e,f,g,h,i,j;
public loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
g = 0;
h = 0;
i = 0;
j = 0;
int asl = as.length();
while(index<asl){
String num3 = as.substring(index,(index+1));
int con3 = Integer.parseInt(num3);
if(con3==9){a++;}
if(con3==8){b++;}
if(con3==7){c++;}
if(con3==6){d++;}
if(con3==5){e++;}
if(con3==4){f++;}
if(con3==3){g++;}
if(con3==2){h++;}
if(con3==1){i++;}
if(con3==0){j++;}
index++;
}
for(int z=0;z<a;z++){
System.out.print("9");
}
for(int y=0;y<b;y++){
System.out.print("8");
}
for(int x=0;x<c;x++){
System.out.print("7");
}
for(int w=0;w<d;w++){
System.out.print("6");
}
for(int v=0;v<e;v++){
System.out.print("5");
}
for(int u=0;u<f;u++){
System.out.print("4");
}
for(int t=0;t<g;t++){
System.out.print("3");
}
for(int s=0;s<h;s++){
System.out.print("2");
}
for(int r=0;r<i;r++){
System.out.print("1");
}
for(int q=0;q<j;q++){
System.out.print("0");
}
public static void main(String []args){
loops x = new loops();
x.biggest(45683408);
}
}
If arrays aren't allowed, then I don't think strings should be allowed either:
static void biggest(int n)
{
long counts=0;
for(; n>0; n/=10)
{
counts += 1L<<((n%10)*4);
}
long result=0;
for (long digit=9; digit>=0; --digit)
{
for(long rep=(counts>>(digit*4))&15; rep>0; --rep)
{
result = result*10 + digit;
}
}
System.out.println(result);
}
The aim is given a file, with the 1st line as the number of lines available, find how many pair of lines are permutations of each other. Example would be that AABA is a permutation of BAAA. The code is written in java. This is my current code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
public class SpeedDemon {
public class Data{
byte[] dataValues;
byte duplicate=1;
int hashcode;
public Data(byte[] input) {
dataValues= new byte[128];
for (byte x : input) {
if (x==10){
break;
}
dataValues[x]++;
}
hashcode = Arrays.hashCode(dataValues);
}
public boolean equal(Data o){
return this.hashcode==o.hashcode&&Arrays.equals(o.dataValues, this.dataValues);
}
}
public int processData(String fileName){
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int size = Integer.parseInt(reader.readLine());
int arr_size = 2;
while (arr_size < size) {
arr_size *= 2;
}
Data[] map = new Data[arr_size];
int z = 0;
Data data;
int j;
for (int i = 0; i < size; i++) {
data = new Data(reader.readLine().getBytes());
j = data.hashcode;
j ^= (j >>> 16);
j &= (arr_size - 1);
while (true) {
if (map[j] == null) {
map[j] = data;
break;
} else {
if (map[j].equal(data)) {
z += map[j].duplicate++;
break;
} else {
j = j == arr_size - 1 ? 0 : j + 1;
}
}
}
}
return z;
}catch(Exception ex){ }
return 0;
}
public static void main(String[] args) {
System.out.println(new SpeedDemon().processData(args[0]));
}
}
I would like to know if there is any way to improve the time efficiency of the program? It is part of my class contest and some people have managed runtimes of around 25% faster. I tried different array sizes and this seem to work the best.
Multiply arr_size by 4. You need a lot of free slots to make open addressing efficient, and depending on what size is you may not be getting very many right now.
Specify a larger buffer size on your buffered reader to reduce the I/O count. 32768 would be reasonable.
Then work on efficiency in Data Both the hashing and comparison operations need to iterate through all 128 possible byte values, which is unnecessary.
Are you sure your code even gets the correct answer? It doesn't seem likely.
The easiest way to determine if two strings are permutations of each other is to sort the strings and compare them. With that in mind, an easier and faster way to code this up would be to use a Map. Something like this:
Create a new Map where the key and value are both strings
for each line of the file
s = read string from file
sortedString = sort(s) // sort characters in the string
if (map.contains(sortedString))
you found a duplicate
else
map.insert(sortedString, string) // the key is the sorted string
end for
There are other ways to do this, but that's the easiest way I know of, and probably the fastest.
I'm new to coding and I've been writing this code and trying to make it work but every time I run it it crashes. I've looked things up and will writing this code I've followed java's website on how to properly write down code as well as this site.
Anyways, it would be greatly appreciated if someone can explain to me why this is not working because it seems to me like the logic is there but I don't get why it crashes.
My code:
import java.util.Scanner;
import java.lang.String;
import java.util.*;
public class Question1
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
System.out.println("Enter either letters or numbers and I'll magically tell you if they are consecutive :D");
String inputedString= keyboard.nextLine();
boolean consecutiveOrNot=isConsecutive(inputedString);
System.out.println("Drum rolls...... Is it consecutive: "+ consecutiveOrNot); //Problem with this line?
}
public static boolean isConsecutive(String inputedString)
{
//Storing string's units into an array and converting to UpperCase if necessary
//and storing string's numerical value into the variable 'arrayCharToInt'
char[] charIntoArray= new char[inputedString.length()];
int[] arrayCharToInt= new int[inputedString.length()];
for (int i=0;i<inputedString.length();i++ )
{
charIntoArray[i]=inputedString.charAt(i);
if (Character.isLetter(charIntoArray[i]) && Character.isLowerCase(charIntoArray[i]))
{
charIntoArray[i]= Character.toUpperCase(charIntoArray[i]);
}
arrayCharToInt[i]=(int) charIntoArray[i];
}
// The next if statements and the methods that they call are used to verify
//that the content of the initial string is either letters or numbers, but not both together
boolean[] continuous= new boolean[arrayCharToInt.length];
boolean[] testContNumbersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContNumbersIncreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersDecreasing= new boolean[arrayCharToInt.length];
boolean[] testContLettersIncreasing= new boolean[arrayCharToInt.length];
Arrays.fill(continuous, true);
if (lowestValue(arrayCharToInt)>=65 && highestValue(arrayCharToInt)<= 90)
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContLettersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -25));
testContLettersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -25));
}
return (Arrays.equals(continuous,testContLettersIncreasing) || Arrays.equals(continuous,testContLettersDecreasing));
}
else if ((lowestValue(arrayCharToInt) >= 48) && (highestValue(arrayCharToInt)<= 57))
{
for (int x=0;x<arrayCharToInt.length ;x++ )
{
testContNumbersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -9));
testContNumbersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -9));
}
return (Arrays.equals(continuous,testContNumbersIncreasing) || Arrays.equals(continuous,testContNumbersDecreasing));
}
else
{
return false;
}
}
public static int lowestValue(int[] array)
{
int lowest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( lowest>array[counter])
lowest= array[counter];
}
return lowest;
}
public static int highestValue(int[] array)
{
int highest=array[0];
for (int counter=0; counter< array.length; counter++)
{
if( highest<array[counter])
highest= array[counter];
}
return highest;
}
}
The main method seems to be fine because it put everything in the isConsecutive method as a comment except for 'return true;' and indeed the program ran and printed true. So I know the problem lies somewhere in the second method.
If there's anything that I did not do right please tell me and that would be greatly appreciated. After all I'm still learning.
Thanks
All of your calls to arrayCharToInt[x+1] are going to go out of bounds on the last iteration of the loop they're in (for example, if arrayCharToInt.length equals 5, the highest that x is going to go is 4. But then x+1 equals 5, which is out of bounds for an array with five cells). You'll need to put in some sort of if( x == arrayCharToInt.length - 1) check.
in the method isConsecutive inside the for loop: for (int x=0;x<arrayCharToInt.length ;x++ ) , you have used arrayCharToInt[x+1]
if the arrayCharToInt lenth is 4 , then you have arrayCharToInt [0] to arrayCharToInt [3].
now consider this statement:arrayCharToInt[x+1]
when x is 3 this statement will evalueate to arrayCharToInt[4] resulting in array index out of bounds exception
This error throw when something went wrong in the Array calling function.
You got the length and make it print.
for eg:
int a[] = {1,2,3,4}
Length of this array is,
int length = a.length
So length = 4 but highest index is 3, not 4. That means index of the array started with 0. So you have to print:
arr[length-1];
In your program,
x == arrayCharToInt.length - 1
I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.
I'm familiar with Levenshtein's distance, so I decided I would use it to solve UVA's Edit Steps Ladder problem.
My solution is:
import java.io.*;
import java.util.*;
class LevenshteinParaElJuez implements Runnable{
static String ReadLn(int maxLength){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte line[] = new byte [maxLength];
int length = 0;
int input = -1;
try{
while (length < maxLength){//Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line ninput
line [length++] += input;
}
if ((input < 0) && (length == 0)) return null; // eof
return new String(line, 0, length);
}catch (IOException e){
return null;
}
}
public static void main(String args[]) // entry point from OS
{
LevenshteinParaElJuez myWork = new LevenshteinParaElJuez(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
public void run(){
ArrayList<String> theWords = new ArrayList<String>();
try
{
/// PLACE YOUR JAVA CODE HERE
String leido=LevenshteinParaElJuez.ReadLn(100);
//System.out.println("lo leido fue "+leido);
while (leido.length() != 0){
theWords.add(leido);
leido=LevenshteinParaElJuez.ReadLn(100);
}
}catch(Exception e){
System.out.println("El programa genero una excepcion");
}
int maxEdit=0;
int actualEdit=0;
int wordsIndex1 =0, wordsIndex2=0;
while (wordsIndex1<= theWords.size())
{
while (wordsIndex2<= theWords.size()-1){
actualEdit=Levenshtein.computeLevenshteinDistance(theWords.get(wordsIndex1),theWords.get(wordsIndex2));
if (actualEdit>maxEdit){maxEdit=actualEdit;}
wordsIndex2++;
}
wordsIndex1++;
}
System.out.println(maxEdit+1);
}
}
class Levenshtein {
private static int minimum(int a, int b, int c) {
if(a<=b && a<=c)
return a;
if(b<=a && b<=c)
return b;
return c;
}
public static int computeLevenshteinDistance(String str1, String str2) {
return computeLevenshteinDistance(str1.toCharArray(),
str2.toCharArray());
}
private static int computeLevenshteinDistance(char [] str1, char [] str2) {
int [][]distance = new int[str1.length+1][str2.length+1];
for(int i=0;i<=str1.length;i++)
distance[i][0]=i;
for(int j=0;j<=str2.length;j++)
distance[0][j]=j;
for(int i=1;i<=str1.length;i++)
for(int j=1;j<=str2.length;j++)
distance[i][j]= minimum(distance[i-1][j]+1,
distance[i][j-1]+1,
distance[i-1][j-1]+
((str1[i-1]==str2[j-1])?0:1));
return distance[str1.length][str2.length];
}
}
With this input:
cat
dig
dog
fig
fin
fine
fog
log
wine
it produces the correct output for this sample:
5
The judge is rejecting my answer. This is my first attempt at solving an online judge's problem, and I think I maybe forcing a correct answer here:
System.out.println(maxEdit+1);
since maxEdit has a value of 4 when computed simply with Levenshtein. Is that what's going on?
Levinshtein is relevant, but will not give you a value used in your output. In this problem, use it to determine if two words have an edit distance of exactly 1, indicating the two words compared are adjacent in the edit step ladder.
Iterate over the words in the dict. and if the next word has an edit distance of 1 from the current word, you may make that the current word, otherwise it must be skipped.
The trick to this problem is finding all possible sequences - just because the next word has an edit distance of 1 doesn't mean using it in the ladder will give you the longest possible ladder.
The problem states that you are to find the longest lexicographically ordered (i.e. alphabetical) sequence in the dictionary, such that each word in the sequence is formed by adding, deleting, or changing one letter.
So the 5 in the sample result is for the sequence (dig, fig, fin, fine, wine).
I don't think Levenshtein is particularly relevant to this problem, though maybe I am just not imaginative enough. Levenshtein doesn't capture the requirement that each step must be in the dictionary, and later in the dictionary.