Пример #1
0
/**
Returns dvector where each element contains the sum total of each row
in matrix.

\param matrix dmatrix
*/
dvector rowsum(const dmatrix& matrix)
{
  int min = matrix.rowmin();
  int max = matrix.rowmax();

  dvector sums(min, max);
  for (int i = min; i <= max; ++i)
  {
    sums(i) = sum(matrix(i));
  }
  return sums;
}
Пример #2
0
vector<T> 
rowSums(matrix<T> &data)
{
	unsigned int rows = data.size1();
	vector<T> sums(rows);

	for(unsigned int i=0; i<rows; i++)
		{
			 matrix_row<matrix<T> > mc (data, i);
			 T s = T(sum(mc));
			 sums(i) = s;
		}
	return sums;
}
Пример #3
0
vector<T> 
colSums(matrix<T> &data)
{
	unsigned int cols = data.size2();
	ublas::vector<T> sums(cols);

	for(unsigned int i=0; i<cols; i++)
		{
			 matrix_column<ublas::matrix<T> > mc (data, i);
			 T s = T(sum(mc));
			 sums(i) = s;
		}
	return sums;
}
Пример #4
0
    /**
     * @param nums: A list of integers
     * @param k: An integer denote to find k non-overlapping subarrays
     * @return: An integer denote the sum of max k non-overlapping subarrays
     */
    int maxSubArray(vector<int> nums, int k) {
        const int n = nums.size();

        // sums[x][y] means the max sum in range [0, x - 1] with y non-overlapping subarrays
        vector<vector<int>> sums(n + 1, vector<int>(k + 1, INT_MIN));

        for (int i = 0; i <= n; ++i) {
            sums[i][0] = 0;
        }

        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= min(i, k); ++j) {
                sums[i][j] = sums[i - 1][j];
                int sum = 0, max_sum = INT_MIN;
                for (int p = i; p > j - 1; --p) {
                    sum += nums[p - 1];
                    max_sum = max(max_sum, sum);
                    sum = max(0, sum);
                    // max sum in range[0, i - 1] with j subarrays equals to
                    // max sum in max(range [0, p - 2] with j - 1 subarrys plus
                    // max sum in range [p - 1, i - 1] with 1 subarray 
                    sums[i][j] = max(sums[i][j], sums[p - 1][j - 1] + max_sum);
                }
            }
        }

        return sums[n][k];
    }
Пример #5
0
  // not fully ac
 vector<int> subarraySumClosest(vector<int> nums){
     // write your code here
     int n=nums.size();
     //sums[i] records sum of [0..i)
     vector<int> sums(n+1,0);
     sums[0]=0;
     vector<int> res;
     
     unordered_map<int,int> mm;
     for(int i=1; i<=n; i++){
         sums[i]=sums[i-1]+nums[i-1];
         mm[sums[i]]=i;
     }
     
     sort(sums.begin(),sums.end());
     int minidx=0;
     int maxidx=0;
     int dist=INT_MAX;
     for(int i=1;i<sums.size(); i++){
         if(sums[i]-sums[i-1]<dist){
             dist=sums[i]-sums[i-1];
             minidx=min(mm[sums[i]],mm[sums[i-1]]);
             maxidx=max(mm[sums[i]],mm[sums[i-1]])-1;
         }
     }
     res.push_back(minidx);
     res.push_back(maxidx);
     
     return res;
 }
Пример #6
0
	std::vector<double> Bagger::distributionForInstance(InstancePtr instance){
		std::vector<double> sums(m_data->getNumClassValues(),0), newProbs;

		for(int i = 0; i < m_NumIterations; i++){
			if(m_data->getClassFormat() == Attribute::IF_NUMERIC) {		
				sums[0] += m_trees[i]->classifyInstance(instance);
			} 
			else{
				newProbs = m_trees[i]->distributionForInstance(instance);
				for (int j = 0; j < newProbs.size(); j++)
					sums[j] += newProbs[j];
			}
		}

		if(m_data->getClassFormat() == Attribute::IF_NUMERIC) {
			sums[0] /= (double) m_NumIterations;
			return sums;
		}
		else if(RandomTree::sum(sums) < 1e-6) {
			return sums;
		}
		else{
			RandomTree::normalize(sums);
			return sums;
		}
	}
		/**
		* @param nums: A list of integers
		* @return: A list of integers includes the index of the first number
		*          and the index of the last number
		*/
		vector<int> subarraySumClosest(vector<int> nums){
			int len = nums.size();
			if (len == 0) return{ -1, -1 };
			if (len == 1) return{ 0, 0 };

			vector<pair<int, int>> sums(len + 1);
			sums[0] = make_pair(0, -1);

			int sum = 0;
			for (int i = 0; i < len; i++)
			{
				sum += nums[i];
				sums[i + 1] = make_pair(sum, i);
			}

			sort(sums.begin(), sums.end());
			int minDiff = INT_MAX;
			int start = -1;
			int end = -1;
			for (int i = 1; i < sums.size(); i++)
			{
				int diff = abs(sums[i].first - sums[i - 1].first);
				if (diff < minDiff)
				{
					minDiff = diff;
					start = min(sums[i].second, sums[i - 1].second) + 1;
					end = max(sums[i].second, sums[i - 1].second);
				}
			}
			return { start, end };
		}
Пример #8
0
void LAP_SQLModel::recalculate()
{

    QVector < double > sums(_column_count,0);
    for (int j=0; j< _data.size()-1; ++j)
        for (int i=1; i< _column_count; ++i)
            if (_isCalc[i])
            {
                if (_neg == 0) sums[i] += _data[j][i].toDouble();
                else
                {
                    if (_data[j][i].toDouble()>=0 && _neg == 1)
                        sums[i] += _data[j][i].toDouble();
                    if (_data[j][i].toDouble()<0 && _neg == 2)
                        sums[i] += _data[j][i].toDouble();

                }
            }
    _data[_row_count-1][0]="";
    for (int i=1; i< _column_count; ++i)
    {
        if (_isCalc[i])
            _data[_row_count-1][i] = sums[i];
        else
            _data[_row_count -1][i] = "";
    }

}
Пример #9
0
 int minimumTotal(vector<vector<int> > &triangle) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     size_t level = triangle.size();
     size_t num = (1 + level) * level / 2;
     vector<int> sums(num);
     
     size_t index = (level - 1) * level / 2;
     for (size_t c = 0; c < level; ++c)
     {
         sums[index + c] = triangle[level - 1][c];
     }
     
     for (int r = level - 2; r >= 0; --r)
     {
         index = (r + 1) * r / 2;
         for (size_t c = 0; c <= r; ++c)
         {
             sums[index + c] = triangle[r][c];
             
             size_t indexL = (r + 2) * (r + 1) / 2 + c;
             size_t indexR = (r + 2) * (r + 1) / 2 + c + 1;
             
             sums[index + c] += std::min(sums[indexL], sums[indexR]);
         }
     }
     return sums[0];  
 }
Пример #10
0
    /**
     * @param nums: A list of integers
     * @param k: An integer denote to find k non-overlapping subarrays
     * @return: An integer denote the sum of max k non-overlapping subarrays
     */
    int maxSubArray(vector<int> nums, int k) {
        const int n = nums.size();

        // sums[x][y] means the max sum in range [0, x - 1] with k non-overlapping subarrays
        vector<vector<int>> sums(n + 1, vector<int>(k + 1, INT_MIN));

        for (int i = 0; i <= n; ++i) {
            sums[i][0] = 0;
        }

        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= min(i, k); ++j) {
                sums[i][j] = sums[i - 1][j];
                int max_sum_from_p = 0;
                for (int p = i; p > j - 1; --p) {
                    max_sum_from_p = max(0, max_sum_from_p) + nums[p - 1];
                    // max sum in range[0, i - 1] with j subarrays equals to
                    // max sum in max(range [0, p - 2] with j - 1 subarrys plus
                    // max sum of the subarray which starts from p - 1 
                    sums[i][j] = max(sums[i][j], sums[p - 1][j - 1] + max_sum_from_p);
                }
            }
        }

        return sums[n][k];
    }
Пример #11
0
 /**
  * @param nums: A list of integers
  * @return: A list of integers includes the index of the first number 
  *          and the index of the last number
  */
 vector<int> subarraySumClosest(vector<int> nums){
     // write your code here
     int size = nums.size();
     vector<int> result;
     if (nums.empty()) {
         return result;
     }
     vector<pair<int, int>> sums(size+1);
     int i;
     for (i=0; i<size; i++) {
         sums[i+1].first = sums[i].first + nums[i];
         sums[i+1].second = i+1;
     }
     sort(sums.begin(), sums.end());
     int min_diff = INT_MAX;
     int sum_diff;
     int index=1;
     for (i=1; i<size+1; i++) {
         sum_diff = abs(sums[i].first - sums[i-1].first);
         if (sum_diff < min_diff) {
             min_diff = sum_diff;
             index = i;
         }
     }
     int left_idx = min(sums[index].second, sums[index-1].second);
     int right_idx = max(sums[index].second, sums[index-1].second)-1;
     result.push_back(left_idx);
     result.push_back(right_idx);
     return result;
 }
Пример #12
0
void Codebook::rescue(vector<int>& temp, cv::Mat& data, int codebook_size)
{
    assert(temp.size() == data.rows);
    vector< vector<float> > sums(codebook_size);
    vector<int> count(codebook_size);
    for (int r=0; r<temp.size(); r++)
    {
        int cl = temp[r];
        count.at(cl)++;
        if (sums[cl].size()==0)
            sums[cl].resize(data.cols,0);
        for (int c=0; c<data.cols; c++)
        {

            sums[cl][c] += data.at<float>(r,c);
        }
    }
    cout << "compiling codebook" << endl;

    for (int cl=0; cl<codebook_size; cl++)
    {
        assert(count[cl]>0);
        vector<double> toAdd;
        for (int c=0; c<data.cols; c++)
        {
            assert(sums[cl][c]>=0);
            toAdd.push_back(sums[cl][c]/count[cl]);
        }
        codebook.push_back(toAdd);
    }

}
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        if (matrix.empty()) {
            return 0;
        }

        const int m = min(matrix.size(), matrix[0].size());
        const int n = max(matrix.size(), matrix[0].size());
        int result = numeric_limits<int>::min();

        for (int i = 0; i < m; ++i) {
            vector<int> sums(n, 0);
            for (int j = i; j < m; ++j) {
                for (int l = 0; l < n; ++l) {
                    sums[l] += (m == matrix.size()) ? matrix[j][l] : matrix[l][j];
                }
    
                // Find the max subarray no more than K.
                set<int> accu_sum_set;
                accu_sum_set.emplace(0);
                int accu_sum = 0;
                for (int sum : sums) {
                    accu_sum += sum;
                    auto it = accu_sum_set.lower_bound(accu_sum - k);
                    if (it != accu_sum_set.end()) {
                        result = max(result, accu_sum - *it);
                    }
                    accu_sum_set.emplace(accu_sum);
                }
            }
        }

        return result;
    }
Пример #14
0
void LAP_SQLModel::fetchMore ( const QModelIndex &)
{
    QVector <QVariant> _temp(header.count());
    int lump = 0;

    do
    {
        _temp.clear();
        for (int i=0; i< header.count(); ++i)
            _temp.push_back(_query.value(i));

        _data.push_back(_temp);
        lump++;
    }while (   lump < max_lump && _query.next() );

    _isall = _query.next();

    _row_count = _data.size();

    //maybe we need to recalculate sums?
    if (!_isall && this->_totals)
    {

        if (_data.size()>0)
        {
            QVector < double > sums(_column_count,0);
            for (int j=0; j< _data.size(); ++j)
                for (int i=1; i< _column_count; ++i)
                    if (_isCalc[i])
                    {
                        if (!_neg) sums[i] += _data[j][i].toDouble();
                        else
                        {
                            if (_data[j][i].toDouble()>=0 && _neg == 1)
                                sums[i] += _data[j][i].toDouble();
                            if (_data[j][i].toDouble()<0 && _neg == 2)
                                sums[i] += _data[j][i].toDouble();
                        }
                    }
            _temp[0]="";
            for (int i=1; i< _column_count; ++i)
            {
                if (_isCalc[i])
                    _temp[i] = sums[i];
                else
                    _temp[i] = "";
            }
            _data.push_back(_temp);
            _row_count++;
        }
    }


   // if (_grid->isAuto)

  emit layoutChanged();
  //_grid->resizeRowsToContents();

}
Пример #15
0
double ABCDCount::GetTotalCount() const{
  std::vector<double> sums(4);
  sums.at(0)=Math::Sum(a_.begin(), a_.begin()+GetNumberOfBins());
  sums.at(1)=Math::Sum(b_.begin(), b_.begin()+GetNumberOfBins());
  sums.at(2)=Math::Sum(c_.begin(), c_.begin()+GetNumberOfBins());
  sums.at(3)=Math::Sum(d_.begin(), d_.begin()+GetNumberOfBins());
  return Math::Sum(sums.begin(), sums.end());
}
Пример #16
0
 int countRangeSum(vector<int>& nums, int lower, int upper) {
     vector<long long> sums(nums.size()+1);
     sums[0]=0;
     for (int i=0; i<nums.size(); ++i)
         sums[i+1] = sums[i]+nums[i];
     tmp=sums;
     return mergeSort(sums, lower, upper, 0, sums.size()-1);
 }
Пример #17
0
NumericVector colSums(NumericMatrix x) {
  int n = x.ncol();
  NumericVector sums(n, 0.0);
  
  for (int c = 0; c < n; ++c)
    sums[c] += sum(x(_, c));
  
  return sums;
}
Пример #18
0
/**
Returns dvector where each element contains the sum total of each column 
in matrix.

\param matrix dmatrix
*/
dvector colsum(const dmatrix& matrix)
{
  int cmin = matrix.colmin();
  int cmax = matrix.colmax();
  int rmin = matrix.rowmin();
  int rmax = matrix.rowmax();

  dvector sums(cmin, cmax);
  sums.initialize();
  for (int j=cmin; j<=cmax; ++j)
  {
    for (int i=rmin; i<=rmax; ++i)
    {
      sums(j) += matrix(i, j);
    }
  }
  return sums;
}
Пример #19
0
NumericVector rowSums(NumericMatrix x) {
  int n = x.nrow();
  NumericVector sums(n, 0.0);
  
  for (int r = 0; r < n; ++r)
    sums[r] += sum(x(r, _));
  
  return sums;
}
Пример #20
0
living *grass::next(world w)
{
  int sum[STATES];
  sums(w, sum);

  if (sum[GRASS] > sum[RABBIT]) // eat grass
    return (new grass(row, column));
  else
    return (new empty(row, column));
}
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DefaultSpmdVectorSpace_Parallel, emptyProcAssignSumMultiVec,
  Scalar )
{
  const Ordinal localDim = g_localDim;
  PRINT_VAR(localDim);
  const RCP<const DefaultSpmdVectorSpace<Scalar> > vs = createZeroEleProcVS<Scalar>(localDim);
  const Ordinal numCols = 3;
  PRINT_VAR(numCols);
  const RCP<MultiVectorBase<Scalar> > mv = createMembers<Scalar>(vs, numCols);
  const Scalar val = 1.5;
  PRINT_VAR(val);
  ECHO(assign(mv.ptr(), as<Scalar>(val)));
  Teuchos::Array<Scalar> sums(numCols);
  Thyra::sums<Scalar>(*mv, sums());
  for (int j = 0; j < numCols; ++j) {
    PRINT_VAR(j);
    TEST_EQUALITY(sums[j],
      as<Scalar>(localDim*(vs->getComm()->getSize()-1))*val);
  }
}
Пример #22
0
void DataMangler::AverageValues(XYGraph *graph) {
	double pvx = pow(0.1, m_di[0]->GetPrec());

	int count;
	double slice;
	double dif = graph->m_dmax[0] - graph->m_dmin[0];
	if (dif < pvx) {
		count = 1;
		slice = pvx;
	} else {
		count = 0;
		while (dif / count > pvx && count < 20)
			++count;
		slice = dif / count;
	}

	std::deque<double> sums(count, 0);
	std::deque<int> counts(count, 0);
	std::deque< std::vector<DTime> > ptimes(count);

	for (size_t i = 0; i < graph->m_points_values.size(); ++i) {
		double& x = graph->m_points_values.at(i).first[0];
		double& y = graph->m_points_values.at(i).first[1];
		std::vector<DTime> &times = graph->m_points_values.at(i).second;

		int idx = int((x - graph->m_dmin[0] - slice / 2) * count / dif);
		if (idx < 0)
			idx = 0;

		if (idx >= count)
			idx = count - 1;

		counts[idx]++;
		sums[idx] += y;
 
		for(unsigned int j = 0; j < times.size(); j++)
			ptimes[idx].push_back(times[j]);
	}

	graph->m_points_values.clear();

	for (int i = 0; i < count; ++i) {
		int c = counts[i];
		if (c == 0)
			continue;

		std::vector<double> xy(2);
		xy[0] = graph->m_dmin[0] + dif * i / count;
		xy[1] = sums[i] / c;

		graph->m_points_values.push_back(XYPoint(xy, ptimes[i]));
	}
			
}
Пример #23
0
void ConfusionMatrix::normalize() {

    if (normalized) {
        throw std::runtime_error("confusion matrix is already normalized");
    }

    cuv::ndarray<double, cuv::host_memory_space> sums(getNumClasses());

    const unsigned int numClasses = getNumClasses();

    for (unsigned int label = 0; label < numClasses; label++) {
        sums(label) = 0.0;
        for (unsigned int prediction = 0; prediction < numClasses; prediction++) {
            double value = static_cast<double>(data(label, prediction));
            sums(label) += value;
        }
    }

    for (unsigned int label = 0; label < numClasses; label++) {
        if (sums(label) == 0.0)
            continue;
        for (unsigned int prediction = 0; prediction < numClasses; prediction++) {
            data(label, prediction) /= sums(label);
        }
    }

#ifndef NDEBUG
    for (unsigned int label = 0; label < numClasses; label++) {
        double sum = 0.0;
        for (unsigned int prediction = 0; prediction < numClasses; prediction++) {
            double v = static_cast<double>(data(label, prediction));
            assert(v >= 0.0 && v <= 1.0);
            sum += v;
        }
        assert(sum == 0.0 || abs(1.0 - sum) < 1e-6);
    }
#endif

    normalized = true;

}
Пример #24
0
living *fox::next(world w)
{
  int sum[STATES];
  sums(w, sum);

  if (sum[FOX] > 5)            // too many foxes
    return (new empty(row, column));
  else if (age > DFOX)         // fox too old
    return (new empty(row, column));
  else
    return (new fox(row, column, age+1));
}
Пример #25
0
living *rabbit::next(world w)
{
  int sum[STATES];
  sums(w, sum);

  if (sum[FOX] >= sum[RABBIT]) // eat rabbits
    return (new empty(row, column));
  else if (age > DRAB)         // rabbit too old
    return (new empty(row, column));
  else
    return (new rabbit(row, column, age+1));
}
Пример #26
0
/*
================================
 prefixSums

 Calculate prefix sums for a given array.
================================
*/
std::vector<int> prefixSums(std::vector<int> array)
{
	int n = array.size();
	std::vector<int> sums(n + 1, 0);

	for (int i = 1; i < n + 1; ++i)
	{
		sums[i] = sums[i - 1] + array[i - 1];
	}

	return sums;
}
 vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) {
     vector<vector<int>> graph(N, vector<int>());
     for (auto edge : edges) {
         graph[edge[0]].push_back(edge[1]);
         graph[edge[1]].push_back(edge[0]);
     }
     
     vector<int> sums(N), counts(N, 1);
     dfs1(0, -1, graph, sums, counts);
     dfs2(0, -1, graph, sums, counts);
     return sums;
 }
Пример #28
0
// Pass 2 computes CSR entries for matrix C = A*B using the
// row pointer Cp[] computed in Pass 1.
void csr_matmat_pass2(const CSRMatrix &A, const CSRMatrix &B, CSRMatrix &C)
{
    std::vector<int> next(A.col_, -1);
    vec_basic sums(A.col_, zero);

    unsigned nnz = 0;

    C.p_[0] = 0;

    for (unsigned i = 0; i < A.row_; i++) {
        int head = -2;
        unsigned length = 0;

        unsigned jj_start = A.p_[i];
        unsigned jj_end = A.p_[i + 1];
        for (unsigned jj = jj_start; jj < jj_end; jj++) {
            unsigned j = A.j_[jj];
            RCP<const Basic> v = A.x_[jj];

            unsigned kk_start = B.p_[j];
            unsigned kk_end = B.p_[j + 1];
            for (unsigned kk = kk_start; kk < kk_end; kk++) {
                unsigned k = B.j_[kk];

                sums[k] = add(sums[k], mul(v, B.x_[kk]));

                if (next[k] == -1) {
                    next[k] = head;
                    head = k;
                    length++;
                }
            }
        }

        for (unsigned jj = 0; jj < length; jj++) {

            if (neq(*sums[head], *zero)) {
                C.j_[nnz] = head;
                C.x_[nnz] = sums[head];
                nnz++;
            }

            unsigned temp = head;
            head = next[head];

            next[temp] = -1; // clear arrays
            sums[temp] = zero;
        }

        C.p_[i + 1] = nnz;
    }
}
Пример #29
0
void SmoothValues( std::vector< PlyValueVertex< Real > >& vertices , const std::vector< std::vector< int > >& polygons , Real min , Real max )
{
	std::vector< int > count( vertices.size() );
	std::vector< Real > sums( vertices.size() , 0 );
	for( int i=0 ; i<polygons.size() ; i++ ) for( int j=0 ; j<polygons[i].size() ; j++ )
	{
		int j1 = j , j2 = (j+1)%polygons[i].size();
		int v1 = polygons[i][j1] , v2 = polygons[i][j2];
		if( vertices[v1].value>min && vertices[v1].value<max ) count[v1]++ , sums[v1] += vertices[v2].value;
		if( vertices[v2].value>min && vertices[v2].value<max ) count[v2]++ , sums[v2] += vertices[v1].value;
	}
	for( int i=0 ; i<vertices.size() ; i++ ) vertices[i].value = ( sums[i] + vertices[i].value ) / ( count[i] + 1 );
}
Пример #30
0
living *empty::next(world w)
{
  int sum[STATES];
  sums(w, sum);

  if (sum[FOX] > 1)
    return (new fox(row, column));
  else if (sum[RABBIT] > 1)         // fox too old
    return (new rabbit(row, column));
  else if (sum[GRASS])
    return (new grass(row, column));
  else
    return (new empty(row, column));
}