class FindMissingNumber {

    protected static Number findSumPattern(BigDecimal[] numbers) {
        if ( numbers == null || numbers.length < MIN_NUMBER_OF_RESTRICTIONS ) {
            return null;
        }
        BigDecimal gap = null;
        Number missingNumber = null;

        BigDecimal a = numbers[0];
        BigDecimal b = numbers[1];
        BigDecimal c = numbers[2];
        BigDecimal d = numbers[3];

        // Uses first four numbers to check if there is a pattern and to
        // calculate the gap between them. One missing value is allowed.
        if ( b.subtract( a ).equals( c.subtract( b ) ) ) {
            gap = b.subtract( a );
        } else if ( c.subtract( b ).equals( d.subtract( c ) ) ) {
            gap = c.subtract( b );
        } else if ( b.subtract( a ).equals( d.subtract( c ) ) ) {
            gap = b.subtract( a );
        } else {
            // No pattern found.
            return null;
        }

        for ( int i = 0; i < (numbers.length - 1); i++ ) {
            BigDecimal first = numbers[i];
            BigDecimal second = numbers[i + 1];

            if ( missingNumber == null && !second.subtract( first ).equals( gap ) ) {
                missingNumber = second.subtract( gap );
            } else if ( !second.subtract( first ).equals( gap ) && missingNumber != null ) {
                // Happends if there is no pattern found, or more than 1
                // missing number.
                return null;
            }
        }

        return missingNumber;
    }

}