[ create a new paste ] login | about

Link: http://codepad.org/GcqGa8Tc    [ raw code | output | fork ]

C++, pasted on Nov 10:
#include <iostream>
using namespace std;

bool find_neg_seq(float * arr, size_t size, size_t from, size_t &beg, size_t &end); 

int main(){
    size_t i, j, k, n;
    size_t beg = -1;//початковий індекс послідовності
    size_t end = -1;//кінцевий   індекс послідовності
    float arr[] = {0, 2, -3.1, -5, 6, 7, -3, -2, -15, 11, 5, -1, -2};  
    n = sizeof(arr) / sizeof(arr[0]);//розраховуємо кількість єлементів масиву
	cout<<"\n\tINPUT  : "<<endl;
	for( i = 0; i < n; i++ )
		cout<<arr[i]<<" ";
	cout<<"\n\tRESULT : "<<endl;
	for( i = 0; i < n; i++ )
	{
		if( find_neg_seq(arr, n, i, j, k) )
		{
			if( end - beg < k - j )
			{
				beg = j;
				end = k;
			}
			i = k;
		}
	}
	if( end == size_t(-1) )
		cout<<"Input array not contain negative numbers"<<endl;
	else
	{
		cout<<"The longest negative sequence is : "<<endl;
		for( i = beg; i < end + 1; i++ )
			cout<<arr[i]<<" ";
		cout<<"it's length : "<<1 + (end - beg)<<endl;
	}
	cin.get();
    return 0;
}

bool find_neg_seq(float * arr, size_t size, size_t from, size_t &beg, size_t &end){
    bool flag = false;
    size_t elem;
    beg = -1;
    end = -1;
    if( arr )
	{
        for( elem = from; elem < size && !flag; elem++ )
		{
            if( arr[elem] < 0 )
			{
				if( beg == size_t(-1) )
					beg  = elem;
				else
					end  = elem;
			}
			else
			{
				flag = (end != size_t(-1));
			}
                
        }
    }
    return flag;
}


Output:
1
2
3
4
5
6

	INPUT  : 
0 2 -3.1 -5 6 7 -3 -2 -15 11 5 -1 -2 
	RESULT : 
The longest negative sequence is : 
-3 -2 -15 it's length : 3


Create a new paste based on this one


Comments: