views:

125

answers:

5

I am working on an algorithm, and I need to be able to pass in a List and see if there are four numbers in a row at any point in the list.

I have been struggling with an easy way to do this... Here is the basic idea.. I would like the fourNumbersInARow() method to return true:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class Numbers {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<Integer>();
        for(int i = 0; i<10; i++){
            numbers.add((new Random().nextInt()));
        }
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        System.out.println(fourNumbersInARow());

    }

    private static boolean fourNumbersInARow() {


    }

}
+6  A: 

Use two variables: last_value and row_count. Going through the list one by one, always look whether the current value is exactly one bigger than the last_value; if yes, increase row_count, if no, reset it to 1. In any case, set last_value to the current value and loop. If at any point row_count becomes 4, return true. If you reach the end of the list, return false.

EDIT: changed counter range to start at 1

Svante
A: 

This sounds a little like a homework question, so I don't want to write out a complete solution. But in your method just iterate through the list. Take the first number and see if the next number comes after the current, if so then set a variable flag with the start position and the current number, on the next iteration through the loop check to see if that value is before the previous the value etc... Once four in a row are found, break out of the loop and return true. If you encounter a number that is no chronologically correct then set a flag(start location) to null or negative and start the process over from the current location in the list.

broschb
+1  A: 

In pseudocode:

consecutiveCount = 1
lastNumber = firstElementInList(list)

for (number in list.fromSecondElement()):
  if (number - lastNumber == 1):
    consecutiveCount++
  else:
    consecutiveCount = 1

  if (consecutiveCount == 4):
    return true

  lastNumber = number

return false

The bottom line is, you'll want to keep track of the last number in that was in the list, and compare it with the current number to see if the difference is 1. In order to remember the last number, a variable such as lastNumber is needed.

Then, in order to keep track of how many consecutive numbers there have been there should be a counter for that as well, which in the example about is the consecutiveCount.

When the condition where four consecutive numbers have occurred, then the method should return true.

coobird
Ah...won't this return true in cases where there are four increments to `consecutiveCount`, rather than four consecutive numbers? (Say: 1, 2, 4, 5, 7, 8, 10, 11 would return true, wouldn't it? I'm not sure this is what the OP was trying to do.)
Ash
@Ash: Good point, thanks for pointing that out!
coobird
I think it should be (number-lastNumber)==1 and not (lastNumber-number)==1 as it stands currently...
antti.huima
@antti.huima: Indeed, thank you!
coobird
If you test it with (1, 2, 3, 4), you see there is an off-by-one error, you have four numbers in a row if consecutiveCount == 3.
hjhill
@hjhill: Edited the post, thanks!
coobird
A: 

Check this Code, this will return true if there a sequence of 4 numbers and else false otherwise

public class FindFourSequence {

    public boolean isFourinRow(ArrayList seqList) {

        boolean flag = false;
        int tempValue = 0;
        int tempValue2 = 0;
        int tempValue3 = 0;
        int tempValue4 = 0;
        Iterator iter = seqList.iterator();
        while(iter.hasNext()){
            String s1 = (String)iter.next();
            tempValue=Integer.valueOf(s1).intValue();
            if(!(iter.hasNext())){
                break;
            }
            String s2 = (String)iter.next();
            tempValue2=Integer.valueOf(s2).intValue();
            if(((tempValue2-tempValue)==1) || (tempValue-tempValue2)==1){
                if(!(iter.hasNext())){
                    break;
                }
                String s3 = (String)iter.next();
                tempValue3=Integer.valueOf(s3).intValue();
                if((tempValue3-tempValue2)==1 || (tempValue2-tempValue3)==1){
                    if(!(iter.hasNext())){
                        break;
                    }
                    String s4 = (String)iter.next();
                    tempValue4=Integer.valueOf(s4).intValue();
                    if((tempValue3-tempValue4==1) || (tempValue4-tempValue3)==1){
                        flag = true;
                        return flag;
                    }
                }
            }
        }

        return flag;
    }

    public static void main(String[] args) throws Exception {

        ArrayList aList = new ArrayList();
        boolean flag = false;
        FindFourSequence example = new FindFourSequence();
        Random random = new Random();
        for (int k = 0; k < 25; k++) {
            int number = random.nextInt(20);
            System.out.println(" the Number is :" + number);
            aList.add("" + number);
        }
/*      aList.add("" + 1);
        aList.add("" + 2);
        aList.add("" + 3);
        aList.add("" + 4);*/
        flag = example.isFourinRow(aList);
        System.out.println(" the result value is : " + flag);

    }
}
harigm
+1  A: 

Here's an implementation in Java.

static boolean fourNumbersInARow(List<Integer> list) {
    int last = 0xFACADE;  // can be any number
    int count = 0;        // important!
    for (int i : list) {
        if (i == last + 1) {
            if (++count == 4) return true;
        } else {
            count = 1;
        }
        last = i;
    }
    return false;
}

Unlike others, this resets the count of numbers in a row to 1 when the sequence is broken (because a number on its own is 1 number in a row). This allows for easier treatment of the first iteration where technically there is no previous number.

polygenelubricants