import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
* @author Mohammad Faisal
*/
public class DetectingCycles {
public static void detectCycle(String input){
System.out.println("received string: "+input);
StringTokenizer token = new StringTokenizer(input, " ");
int[] nums = new int[token.countTokens()];
for(int i=0; i<nums.length; i++){
nums[i] = Integer.parseInt(token.nextToken());
}
System.out.println("printing the int array");
for(int i=0; i<nums.length; i++){
System.out.print(nums[i]+" ");
}
System.out.println();
for(int i=0; i<nums.length-1; i++){
String a="";
String b="";
boolean found = false;
int limit = (nums.length-i)/2;
int j=i;
for(int l=1; l<=limit; l++){
a+=nums[j]+" ";
int k=j+1;
//here the logic fails for numbers with more than 1 digit.
for(int m=0; m<a.length()/2; m++){
b+=nums[k]+" ";
k++;
}
System.out.println(a+"\t"+b);
if(a.equals(b)){
System.out.println(a.trim()+" found");
found=true;
break;
}else{
b="";
j++;
}
}
if(found){
break;
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileInputStream(args[0]));
while(input.hasNextLine()){
detectCycle(input.nextLine());
}
}
}
The logic is working well for the numbers with only 1 digit but fails for the numbers with more than 1 digit.
Is there any better solution for this problem?

New Topic/Question
Reply




MultiQuote



|