コード例 #1
0
  bool getVersion_(const String& version, MyriMatchVersion& myrimatch_version_i) const
  {
    // we expect three components
    IntList nums = ListUtils::create<Int>(ListUtils::create<String>(version, '.'));
    if (nums.size() != 3) return false;

    myrimatch_version_i.myrimatch_major = nums[0];
    myrimatch_version_i.myrimatch_minor = nums[1];
    myrimatch_version_i.myrimatch_patch = nums[2];
    return true;
  }
コード例 #2
0
ファイル: objectbase.cpp プロジェクト: idrassi/wxFormBuilder
wxArrayInt ObjectBase::GetPropertyAsArrayInt(const wxString& pname)
{
	wxArrayInt array;
	shared_ptr<Property> property = GetProperty( pname );
	if (property)
	{
		IntList il;
		il.SetList(property->GetValue());
		for (unsigned int i=0; i < il.GetSize() ; i++)
			array.Add(il.GetValue(i));
	}

	return array;
}
コード例 #3
0
ファイル: ParsedEntity.cpp プロジェクト: Flewp/TextGame
IntList ParsedEntity::getIntList()
{
	auto pList = getList();
	auto list = *pList;
	IntList retList = MakeIntList();
	for (ParsedEntityPtr pe : list)
	{
		if (pe->getType() == ParsedEntity::Int)
		{
			retList->push_back(pe->getInt());
		}
	}
	return retList;
}
コード例 #4
0
void WQQuiz::addToList(int aCol, int bCol)
{
  //build a list of row numbers containing text in both columns

  typedef QValueList<int> IntList;
  IntList tempList;
  for (int current = 0; current < m_table ->numRows(); ++current)
  {
    if (!m_table->text(current, 0).isEmpty() && !m_table->text(current, 1).isEmpty())
    {
      tempList.append(current);
    }
  }

  KRandomSequence *rs = new KRandomSequence(0);

  int count = tempList.count();

  IntList::ConstIterator it;
  for ( it = tempList.begin(); it != tempList.end(); ++it )
  {
    WQListItem *li;
    li = new WQListItem();
    li->setQuestion(aCol);
    li->setCorrect(1);
    li->setOneOp(*it);

    if (count > 2)
    {

      int a, b;
      do
        a = rs->getLong(count); //rand() % count;
      while(a==*it);

      li->setTwoOp(a);

      do
        b = rs->getLong(count); //rand() % count;
      while(b == *it || b == a /*|| b < 0*/);

      li->setThreeOp(b);

    }
    m_quizList.append(*li);

  }

}
コード例 #5
0
ファイル: DefaultHttpHeader.cpp プロジェクト: frankee/Cetty
void DefaultHttpHeader::set(const std::string& name, const IntList& values) {
    StringList list;
    for (size_t i = 0; i < values.size(); ++i) {
        list.push_back(Integer::toString(values[i]));
    }
    set(name, list);
}
コード例 #6
0
ファイル: radix.cpp プロジェクト: Flameeyes/stdcxx
int main () {
    
    std::cout << "Radix sort program"  << std::endl;

    const IntList::value_type data[] = { 624, 852, 426, 987, 269,
                                       146, 415, 301, 730, 78, 593 };

    IntList values (data, data + sizeof data / sizeof *data);

    radixSort (values);
    std::copy (values.begin (), values.end (), OstreamIter (std::cout, " "));

    std::cout << std::endl << "End radix sort program" << std::endl;

    return 0;   
}
コード例 #7
0
ファイル: radix.cpp プロジェクト: Flameeyes/stdcxx
void radixSort (IntList & values) {
    bool flag   = true;
    int divisor = 1;
    
    while (flag)
    {
        DeqVector buckets (10);
        flag = false;

        std::for_each (values.begin (), values.end (), 
            copyIntoBuckets (divisor, buckets, flag));
        std::accumulate (buckets.begin (), buckets.end (), values.begin (), copyList);
        divisor *= 10;
        std::copy (values.begin (), values.end (), OstreamIter (std::cout, " "));
        std::cout << std::endl;
    }
}
コード例 #8
0
ZoomSettingsWidget::ZoomSettingsWidget(QWidget *parent) :
    QGroupBox(parent),
    m_zoomCombo(new QComboBox)
{
    m_zoomCombo->setEditable(false);
    const IntList zoomValues = ZoomMenu::zoomValues();
    const IntList::const_iterator cend = zoomValues.constEnd();
    //: Zoom percentage
    for (IntList::const_iterator it = zoomValues.constBegin(); it != cend; ++it)
        m_zoomCombo->addItem(QCoreApplication::translate("FormEditorOptionsPage", "%1 %").arg(*it), QVariant(*it));

    // Layout
    setCheckable(true);
    setTitle(QCoreApplication::translate("FormEditorOptionsPage", "Preview Zoom"));
    QFormLayout *lt = new QFormLayout;
    lt->addRow(QCoreApplication::translate("FormEditorOptionsPage", "Default Zoom"), m_zoomCombo);
    setLayout(lt);
}
コード例 #9
0
ファイル: fiducialdata.cpp プロジェクト: GunioRobot/ofxPrimes
int * FiducialData::parseSequenceL( const char * in_fiducialSequence, bool& white ){
	// decode the string, which is assumed to be in the form
	// "a[0], a[1], .., a[N-1]"
	char stringcopy[512] = {0};
	char *tmp = stringcopy;
	strcpy(tmp, in_fiducialSequence);

	// strip [, {, or (
	while( (*tmp == '[' || *tmp == '{' || *tmp == '(' || *tmp == ' ') && *tmp != 0 ){
		tmp++;
	}
	
	white = false;
	IntList * result = IntList::newL();
	for(char * tok = strtok( tmp, "," );tok!=NULL;tok = strtok( NULL, "," )){
		if( atoi(tok)==0 && strchr(tok,'0')==NULL ){
			if( strchr(tok,'w')!=NULL || strchr(tok,'W')!=NULL ){
				white = true;
			}
		}else{
			result->appendL( atoi(tok) );
		}
	}
	
	if( result->getSize() < 2 ){
		delete result;
		return NULL;
	}

	#ifndef __SYMBIAN32__
	int * toReturn = new int[result->getSize()+1];
	#else
	int * toReturn = new (ELeave) int[result->getSize()+1];
	#endif
	
	int i=0;
	toReturn[i++] = result->getSize();
	for(result->reset();!(result->isNull());result->fwd()){
		toReturn[i++] = result->getData();
	}
	delete result;
	
	return toReturn;
}
コード例 #10
0
ファイル: Check.cpp プロジェクト: bhuWenDongchao/pytorch
void checkSize(CheckedFrom c, const TensorGeometryArg& t, IntList sizes) {
  checkDim(c, t, sizes.size());
  if (!t->sizes().equals(sizes)) {
    std::ostringstream oss;
    oss << "Expected tensor of size " << sizes << ", but got tensor of size "
        << t->sizes() << " for " << t
        << " (while checking arguments for " << c << ")";
    throw std::runtime_error(oss.str());
  }
}
コード例 #11
0
ファイル: main.cpp プロジェクト: IronPeak/Gagnaskipan
int main()
{
    IntList list;

    while(true)
    {
        string cmd;
        cin >> cmd;
        if(cmd == "append")
        {
            int elem;
            cin >> elem;
            list.append(elem);
        }
        if(cmd == "remove")
        {
            int index;
            cin >> index;
            list.remove(index);
        }
コード例 #12
0
ファイル: gpsimprocessor.cpp プロジェクト: appillai/ktechlab
void GpsimDebugger::setBreakpoints( const QString & path, const IntList & lines )
{
	for ( unsigned i = 0; i < m_addressSize; i++ )
	{
		DebugLine * dl = m_addressToLineMap[i];
		if ( !dl || dl->fileName() != path )
			continue;

		dl->setBreakpoint( lines.contains( dl->line() ) );
	}
}
コード例 #13
0
ファイル: Type.cpp プロジェクト: HustlehardInc/pytorch
static int64_t computeStorageSize(IntList sizes, IntList strides) {
  // size of the underlying storage is 1 bigger than the offset
  // of the last element according to stride
  int64_t size = 1;
  for(size_t i = 0; i < sizes.size(); i++) {
    if(sizes[i] == 0) {
      return 0;
    }
    size += strides[i]*(sizes[i]-1);
  }
  return size;
}
コード例 #14
0
ファイル: fast-list_test.cpp プロジェクト: ColinGilbert/mili
static bool compare(const IntList& flist, const std::list<int>& l)
{
    if (flist.size() == l.size())
    {
        IntList::ConstElementHandler h(flist.first());
        std::list<int>::const_iterator it = l.begin();

        bool equals = true;
        while (h.is_valid() && equals)
        {
            equals = *h == *it;
            ++h;
            ++it;
        }
        return equals;
    }
    else
    {
        return false;
    }
}
コード例 #15
0
static PyObject * THPVariable_stride(PyObject* self, PyObject* args, PyObject* kwargs)
{
  HANDLE_TH_ERRORS
  static PythonArgParser parser({
    "stride(int64_t dim)",
    "stride()",
  });
  auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
  ParsedArgs<3> parsed_args;
  auto r = parser.parse(args, kwargs, parsed_args);
  if (r.idx == 0) {
    return wrap(self_.stride(r.toInt64(0)));
  } else if (r.idx == 1) {
    // yes, this is called strides in ATen.
    IntList strides = self_.strides();
    // we can't do the normal wrapping here because IntList maps to both
    // torch.Size and tuple in python
    return THPUtils_packInt64Array(strides.size(), strides.data());
  }
  Py_RETURN_NONE;
  END_HANDLE_TH_ERRORS
}
コード例 #16
0
ファイル: FxParser.cpp プロジェクト: 2php/nvFX
 int *flattenIVecList(int t, int vecDim, IntVecList* pintVecList)
 {
     int szvec = 0;
     int *array = NULL;
     // walk through the vector list and check few things then send the packed version
     int *p = NULL;
     if (NULL == pintVecList)
       return 0;
     for(int i=0; i<(int)pintVecList->size(); i++)
     {
         if(szvec == 0) {
             szvec = (int)((*pintVecList)[i]->size());
             p = array = new int[szvec * pintVecList->size()]; // we assume all vectors are the same size
         }
         else if(szvec != (*pintVecList)[i]->size()) {
             yyerror("Vector list has inconsistent vectors\n");
             continue;
         }
         IntList* pfl = (*pintVecList)[i];
         if (NULL!=pfl)
         {
         for(int j=0; j<(int)pfl->size(); j++)
             *p++ = (*pfl)[j];
         delete pfl;
           pfl = NULL;
         }
     }
     if(vecDim < 0)
         vecDim = (int)pintVecList->size();
     // we do the test here in any case : the previous loop needed to do some "delete" anyways
     if((szvec != vecDim) || (t != pintVecList->size()))
     {
         yyerror("Vector dimension in value assignment don't match the type\n");
         delete array;
         return NULL;
     }
     return array;
 }
コード例 #17
0
ファイル: Triangles.cpp プロジェクト: nixz/covise
//provides the index of the highest triangle of a set
//criterion are the normalised 2D-euclidean coordinates
int getHighest(trivec &triangles, ivec &index, IntList &list, bool sorted)
{
    /* 
      int i = 0;
      int ind = 0;

      for(i = 0 ; i < index.size(); i++)
      {
         ind = index[i];
         if( sorted == true )
         {
            if( (triangles[ind]).getPacked() == true )
            {
   continue;
   }
   else
   {
   break;
   }
   }
   else
   {
   cout << "\n... i don't like to run after special\n\ 
   elements in non-sorted lists ...\n" << flush;
   }
   }
   */
    int j = list.getStart();
    int el = list.getElement(j);
    //cout << "\nlist index  : " << flush << j << flush;
    //cout << "\nlist element: " << flush << el << flush;
    //cout << '\n' << flush;
    list.remove(j);

    return el;
}
コード例 #18
0
ファイル: Conv.cpp プロジェクト: HustlehardInc/pytorch
std::vector<int64_t> conv_output_size(
    IntList input_size, IntList weight_size,
    IntList padding, IntList stride, IntList dilation)
{
  auto dim = input_size.size();
  std::vector<int64_t> output_size(dim);
  output_size[0] = input_size[input_batch_size_dim];
  output_size[1] = weight_size[weight_output_channels_dim];
  for (size_t d = 2; d < dim; ++d) {
    auto kernel = dilation[d - 2] * (weight_size[d] - 1) + 1;
    output_size[d] = (input_size[d] + (2 * padding[d - 2])
                        - kernel) / stride[d - 2] + 1;
  }
  return output_size;
}
コード例 #19
0
ファイル: 3-ConShelling1.cpp プロジェクト: beauby/pigale
void KantShelling::SetAdjFaces()  
/* set Brin2Face, Face2Brin, IsOuterV, IsOuterE.
       b = Face2Brin[num]
       b and acir[b] defines an angle
       Moving along a face: cir[-b] or -acir[b]
    */
  {tbrin b, b0;
  // Mark the vertices incident to the last face
  Prop<short> ecolor(G.Set(tedge()),PROP_COLOR);
  Prop<int> ewidth(G.Set(tedge()),PROP_WIDTH);
  b = b0 = FirstBrin();
  do
      {BelongToLastFace[G.vin[b]()] = 1;
      if(debug()) {ecolor[b.GetEdge()] = Green2;ewidth[b.GetEdge()] = 3;}
      }while((b = -G.cir[b]) != b0);

  IntList Brins;  // Brins: list of all brins 
  for(int i = -G.ne();i <= G.ne();i++)
      if(i)Brins.push(i);
  // the edge {v_1,v_2}. IsOuterE is set to 0.
  Brin2Face[FirstBrin()]=1;			  
  IsOuterV[v_1] = 1;
  Brins.del(FirstBrin());

  // the outer face is indexed 1
  b = G.cir[-FirstBrin];
  do 
      {Brins.del(b());
      Brin2Face[b()] = 1;
      IsOuterE[b.GetEdge()] = 1;
      IsOuterV[G.vin[b]()] = 1;
      }while ((b = G.cir[-b])  != FirstBrin);
  Face2Brin[1]=FirstBrin();

  // indexing other faces.
  int FaceIndex=2;
  while (!Brins.empty()) 
      {b0 = b =Brins.first();
       if(debug())cout << "face:" << FaceIndex << endl;
      do 
          {Brins.del(b());
          Brin2Face[b]=FaceIndex;
           if(debug())cout << G.vin[b]() << " " <<endl;
          } 
      while((b = G.cir[-b]) != b0);

      Face2Brin[FaceIndex]=b();
      FaceIndex++;
      }
  }
コード例 #20
0
ファイル: 3-ConShelling1.cpp プロジェクト: beauby/pigale
void KantShelling::UpdateSepf1(IntList &NewSepFaces)
// for all f \in NewxSepFaces, for all v incident
// to f, sepf[v]++.
  {tbrin b, b0;
  int f;
  NewSepFaces.ToHead();
  while ((f=~NewSepFaces)!=0)
      {b0=b=Face2Brin[f];
      do 
          {if(IsOuterV[G.vin[b]()]) _sepf(G.vin[b](),1);
          b=G.cir[-b];
          } 
      while (b!=b0);
      ++NewSepFaces;
      }
  }
コード例 #21
0
bool should_expand(const IntList &from_size, const IntList &to_size) {
  if(from_size.size() > to_size.size()) {
    return false;
  }
  for (auto from_dim_it = from_size.rbegin(); from_dim_it != from_size.rend(); ++from_dim_it) {
    for (auto to_dim_it = to_size.rbegin(); to_dim_it != to_size.rend(); ++to_dim_it) {
      if (*from_dim_it != 1 && *from_dim_it != *to_dim_it) {
        return false;
      }
    }
  }
  return true;
}
コード例 #22
0
ファイル: test_main.cpp プロジェクト: zfbp/scgl
bool Init()
{
	int nRandom = 0;
	for (int i = 0; i < g_nMax; ++i)
	{
		nRandom = i;
		g_nSummary += nRandom;
		g_dInts.push_back(nRandom);
		g_hmInts.insert(std::make_pair(nRandom, nRandom));
		g_hsInts.insert(nRandom);
		g_lInts.push_back(nRandom);
		g_mInts.insert(std::make_pair(nRandom, nRandom));
		g_mmInts.insert(std::make_pair(nRandom, nRandom));
		g_msInts.insert(nRandom);
		g_sInts.insert(nRandom);
		g_vInts.push_back(nRandom);
	}
	return true;
}
コード例 #23
0
ファイル: 3-ConShelling1.cpp プロジェクト: beauby/pigale
void KantShelling::UpdateSepf2(IntList &NewOuterVertices)
// for all v \in NewOuterVertices, recalculate sepf[v].
  {tbrin b, b0;
  int f;
  NewOuterVertices.ToHead();
  int vi, count;
  while ((vi=~NewOuterVertices)!=0)
      {count=0;
      b0=b=G.FirstBrin(vi);
      do 
          {f=Brin2Face[b];
          if(!MarkedF[f] && (outv[f]>=3 || (outv[f]==2 && oute[f]==0))) 
              count++;
          b=G.cir[b];
          }
      while (b!=b0);
      _sepf(vi,count-sepf[vi]);
      ++NewOuterVertices;
      }
  } 
コード例 #24
0
ファイル: tensor_new.cpp プロジェクト: bhuWenDongchao/pytorch
static void recursive_store(char* data, IntList sizes, IntList strides, int64_t dim,
                            ScalarType scalarType, int elementSize, PyObject* obj) {
  int64_t ndim = sizes.size();
  if (dim == ndim) {
    torch::utils::store_scalar(data, scalarType, obj);
    return;
  }

  auto n = sizes[dim];
  auto seq = THPObjectPtr(PySequence_Fast(obj, "not a sequence"));
  if (!seq) throw python_error();
  auto seq_size = PySequence_Fast_GET_SIZE(seq.get());
  if (seq_size != n) {
    throw ValueError("expected sequence of length %lld at dim %lld (got %lld)",
      (long long)n, (long long)dim, (long long)seq_size);
  }

  PyObject** items = PySequence_Fast_ITEMS(seq.get());
  for (int64_t i = 0; i < n; i++) {
    recursive_store(data, sizes, strides, dim + 1, scalarType, elementSize, items[i]);
    data += strides[dim] * elementSize;
  }
}
コード例 #25
0
ファイル: watershed.cpp プロジェクト: pmarais/EBImage
double
check_multiple( double * tgt, double * src, int & ind, IntList & nb, SeedList & seeds, double & tolerance, int & nx, int & ny ) {
    if ( nb.size() == 1 ) return nb.front();
    if ( nb.size() <  1 ) return 0.0; // dumb protection

    double diff, maxdiff = 0.0, res = 0.0;
    int i;
    IntList::iterator  it;
    SeedList::iterator sit;
    PointXY ptsit, pt = pointFromIndex( ind, nx );
    double distx, dist = FLT_MAX;

    /* maxdiff */
    for ( it = nb.begin(); it != nb.end(); it++ ) {
        if ( !get_seed( seeds, *it, sit ) ) continue;
        diff = fabs( src[ ind ] - src[ (*sit).index ] );
        if ( diff > maxdiff ) {
            maxdiff = diff;
            /* assign result to the steepest until and if it not assigned to closest over the tolerance */
            if ( dist == FLT_MAX )
                res = *it;
        }
        /* we assign to the closest centre which is above tolerance, if none than to maxdiff */
        if ( diff >= tolerance ) {
            ptsit = pointFromIndex( (*sit).index, nx );
            distx = distanceXY( pt, ptsit);
            if ( distx < dist ) {
                dist =  distx;
                res = * it;
            }
        }

    }
    /* assign all that need assignment to res, which has maxdiff */
    for ( it = nb.begin(); it != nb.end(); it++ ) {
        if ( *it == res ) continue;
        if ( !get_seed( seeds, *it, sit ) ) continue;
        if ( fabs( src[ ind ] - src[ (*sit).index ] ) >= tolerance ) continue;
        for ( i = 0; i < nx * ny; i++ )
            if ( tgt[ i ] == *it )
                tgt[ i ] = res;
        seeds.erase( sit );
    }
    return res;
}
コード例 #26
0
ファイル: Pooling.cpp プロジェクト: HustlehardInc/pytorch
std::tuple<Tensor,Tensor> max_pool1d(
    const Tensor & self, IntList kernel_size, IntList stride, IntList padding,
    IntList dilation, bool ceil_mode) {

  if (stride.empty()) {
    stride = kernel_size;
  }
  checkDim("max_pool1d", TensorArg(self, "self", 1), 3);
  check1d("kernel_size", kernel_size);
  check1d("stride", stride);
  check1d("padding", padding);
  check1d("dilation", dilation);

  Tensor output, indices;
  std::tie(output, indices) = at::max_pool2d(
      self.unsqueeze(2),
      {1, kernel_size[0]},
      {1, stride[0]},
      {0, padding[0]},
      {1, dilation[0]},
      ceil_mode);

  return std::make_tuple(output.squeeze(2), indices.squeeze(2));
}
コード例 #27
0
ファイル: utils.cpp プロジェクト: frasercrmck/columbo
// Given a list of lists of possible cage values:
//     [[1,2,3], [3,4,5]]
// Recursively generates tuples of combinations from each of the lists as
// follows:
//   [1,3]
//   [1,4]
//   [1,5]
//   [2,3]
//   [2,4]
// ... etc
// Each of these is checked against the target sum, and pushed into a result
// vector if they match.
// Note: The algorithm assumes that the list of possibles/candidates are
// ordered. This allows it to bail out early if it detects there's no point
// going further.
static void subsetSum(const std::vector<IntList> &possible_lists,
                      const std::size_t p_size, IntList &tuple,
                      unsigned tuple_sum, std::vector<IntList> &subsets,
                      const unsigned target_sum, unsigned list_idx) {
  for (unsigned p = list_idx; p < p_size; ++p) {
    for (auto &poss : possible_lists[p]) {
      // Optimization for small target sums: if the candidate is bigger than
      // the target itself then it can't be valid, neither can any candidate
      // after it (ordered).
      if (target_sum < static_cast<unsigned>(poss)) {
        break;
      }

      // Can't repeat a value inside a cage
      if (std::find(tuple.begin(), tuple.end(), poss) != tuple.end()) {
        continue;
      }

      // Pre-calculate the new tuple values to avoid spurious
      // insertions/deletions to the vector.
      const auto new_tuple_sum = tuple_sum + poss;
      const auto new_tuple_size = tuple.size() + 1;

      // If we've added too much then we can bail out (ordered).
      if (new_tuple_sum > target_sum) {
        break;
      }

      // If there are fewer spots left in the tuple than there are options for
      // the sum to reach the target, bail.
      // TODO: This could be more sophisticated (can't have more than one 1, so
      // it's more like the N-1 sum that it should be greater than.
      if ((p_size - new_tuple_size) > (target_sum - new_tuple_sum)) {
        break;
      }

      if (new_tuple_size == p_size) {
        // If we've reached our target size then we can stop searching other
        // possiblities from this list (ordered).
        if (new_tuple_sum == target_sum) {
          tuple.push_back(poss);
          subsets.push_back(tuple);
          tuple.pop_back();
          break;
        }

        // Else, move on to the next candidate in the list.
        continue;
      }

      tuple_sum += poss;
      tuple.push_back(poss);

      subsetSum(possible_lists, p_size, tuple, tuple_sum, subsets, target_sum,
                p + 1);

      tuple.pop_back();
      tuple_sum -= poss;
    }
  }
}
コード例 #28
0
ファイル: main.cpp プロジェクト: achen067/CS14-SPRING2015
int main()
{
    IntList test;
    
    test.push_front(5);
    test.push_front(2);
    test.push_front(5);
    test.push_front(7);
    test.push_front(5);
    
    cout << "Should display counting down from five: ";
    test.display();
    
    cout << endl;
    
    test.push_back(6);
    
    cout << "Should add zero to the end: ";
    
    test.display();
    
    cout << endl;
    
    //test.insert_sorted(3);
    
    test.select_sort();
    
    cout << "Should be in order now: ";
    
    test.display();
    
    cout << endl;
    
    test.remove_duplicates();
    
    cout << "Should remove all same digits: ";
    
    test.display();
    
    cout << endl;
}
コード例 #29
0
ファイル: watershed.cpp プロジェクト: pmarais/EBImage
/*----------------------------------------------------------------------- */
SEXP
watershed (SEXP x, SEXP _tolerance, SEXP _ext) {
    SEXP res;
    int im, i, j, nx, ny, nz, ext, nprotect = 0;
    double tolerance;

    nx = INTEGER ( GET_DIM(x) )[0];
    ny = INTEGER ( GET_DIM(x) )[1];
    nz = getNumberOfFrames(x,0);
    tolerance = REAL( _tolerance )[0];
    ext = INTEGER( _ext )[0];

    PROTECT ( res = Rf_duplicate(x) );
    nprotect++;
  
    int * index = new int[ nx * ny ];

    for ( im = 0; im < nz; im++ ) {

        double * src = &( REAL(x)[ im * nx * ny ] );
        double * tgt = &( REAL(res)[ im * nx * ny ] );

        /* generate pixel index and negate the image -- filling wells */
        for ( i = 0; i < nx * ny; i++ ) {
	  tgt[ i ] = -src[ i ];
	  index[ i ] = i;
        }
        /* from R includes R_ext/Utils.h */
        /* will resort tgt as well */
        rsort_with_index( tgt, index, nx * ny );
        /* reassign tgt as it was reset above but keep new index */
        for ( i = 0; i < nx * ny; i++ )
            tgt[ i ] = -src[ i ];

        SeedList seeds;  /* indexes of all seed starting points, i.e. lowest values */

        IntList  equals; /* queue of all pixels on the same gray level */
        IntList  nb;     /* seed values of assigned neighbours */
        int ind, indxy, nbseed, x, y, topseed = 0;
        IntList::iterator it;
        TheSeed newseed;
        PointXY pt;
        bool isin;
        /* loop through the sorted index */
        for ( i = 0; i < nx * ny && src[ index[i] ] > BG; ) {
            /* pool a queue of equally lowest values */
            ind = index[ i ];
            equals.push_back( ind );
            for ( i = i + 1; i < nx * ny; ) {
                if ( src[ index[i] ] != src[ ind ] ) break;
                equals.push_back( index[i] );
                i++;
            }
            while ( !equals.empty() ) {
                /* first check through all the pixels if we can assign them to
                 * existing objects, count checked and reset counter on each assigned
                 * -- exit when counter equals queue length */
                for ( j = 0; j < (int) equals.size(); ) {
		  if ((j%1000)==0) R_CheckUserInterrupt();
                    ind = equals.front();
                    equals.pop_front();
                    /* check neighbours:
                     * - if exists one, assign
                     * - if two or more check what should be combined and assign to the steepest
                     * - if none, push back */
                    /* reset j to 0 every time we assign another pixel to restart the loop */
                    nb.clear();
                    pt = pointFromIndex( ind, nx );
                    /* determine which neighbour we have, push them to nb */
                    for ( x = pt.x - ext; x <= pt.x + ext; x++ )
                        for ( y = pt.y - ext; y <= pt.y + ext; y++ ) {
                            if ( x < 0 || y < 0 || x >= nx || y >= ny || (x == pt.x && y == pt.y) ) continue;
                            indxy = x + y * nx;
                            nbseed = (int) tgt[ indxy ];
                            if ( nbseed < 1 ) continue;
                            isin = false;
                            for ( it = nb.begin(); it != nb.end() && !isin; it++ )
                                if ( nbseed == *it ) isin = true;
                            if ( !isin ) nb.push_back( nbseed );
                        }
                    if ( nb.size() == 0 ) {
                        /* push the pixel back and continue with the next one */
                        equals.push_back( ind );
                        j++;
                        continue;
                    }
                    tgt[ ind ] = check_multiple(tgt, src, ind, nb, seeds, tolerance, nx, ny );
                    /* we assigned the pixel, reset j to restart neighbours detection */
                    j = 0;
                }
                /* now we have assigned all that we could */
                if ( !equals.empty() ) {
                    /* create a new seed for one pixel only and go back to assigning neighbours */
                    topseed++;
                    newseed.index = equals.front();
                    newseed.seed = topseed;
                    equals.pop_front();
                    tgt[ newseed.index ] = topseed;
                    seeds.push_back( newseed );
                }
            } // assigning equals
        } // sorted index

        /* now we need to reassign indexes while some seeds could be removed */
        double * finseed = new double[ topseed ];
        for ( i = 0; i < topseed; i++ )
            finseed[ i ] = 0;
        i = 0;
        while ( !seeds.empty() ) {
            newseed = seeds.front();
            seeds.pop_front();
            finseed[ newseed.seed - 1 ] = i + 1;
            i++;
        }
        for ( i = 0; i < nx * ny; i++ ) {
            j = (int) tgt[ i ];
            if ( 0 < j && j <= topseed )
                tgt[ i ] = finseed[ j - 1 ];
        }
        delete[] finseed;

    } // loop through images

    delete[] index;

    UNPROTECT (nprotect);
    return res;
}
コード例 #30
0
ファイル: main.cpp プロジェクト: evsukov89/oop_lab2
int main (int argc, char * const argv[]) {
    cout << "running some tests...\n";
    cout << "default constructor:\n";
    IntList list;
    cout << "list.toString() method: "<< list.toString() << endl;
    cout << "list.push:\npush(20)\npush(30)\npush(40)\n"; 
    list.push(20);
    list.push(30);
    list.push(40);
    cout << list.toString() << endl;
    cout << "indexing:\nlist[2] => " << list[2] << endl;
    cout << "list[2] <= 3 : ";
    list[2] = 3;
    cout << list << endl;
    cout << "list.pop():\n";
    cout << "pop():" << list.pop() << endl;
    cout << "pop():" << list.pop() << endl;
    cout << "pop():" << list.pop() << endl;
    cout << "constructor with params (1 25 8):\n";
    IntList list2("(1 25 8)");
    cout << "stream output: list2 = " << list2 << endl;
    cout << "copy-constructor: IntList list3(list2) :";
    IntList list3(list2);
    cout << list3 << endl;
    cout << "pseudo-variables: list3(0,2):"<< list3(0,2) << endl;

    cout << "stream input:"; cin >> list;
    cout << "list = " << list << endl;
    cout << "writing list to file \"list.txt\"";

//    ofstream data("list.txt", ios_base::out||ios_base::trunc);
    ofstream data("list.txt", ios_base::out);
    data << list;
    data.close();
    cout << " ok\n";
    cout << "reading list from file \"list.txt\": ";
    IntList list4;
    ifstream data_in("list.txt", ios_base::in);
    data_in >> list4;
    data_in.close();
    cout << list4 << endl;
    
    cout << "\nstarting program\n";
    map<string, IntList*> lists;
    cout << "hello, Master of the universe, please enter your commands" << endl;
    string input;
    do {
        cout << ">> ";
        getline(cin, input);
        if (input[0] == '(' && input[input.size()-1] == ')') {
            //убираем скобки
            input = input.substr(1, input.size()-2);
            //комманда присваивания
            if (input[0] == '='){
                //убираем равно и пробел после него
                input = input.substr(2, input.size()-2);
                //получем имя списка
                int next_space = input.find_first_of(' ', 0);
                string list_name = input.substr(0, next_space);
                input = input.substr(next_space+1, input.size()-next_space-1);
//                cout << input << endl;
                if (input.substr(0,7) == "(append") {
                    //получается что новый список - какой-то существующий + что допишут
                    input = input.substr(8, input.size()-9);
//                    cout << input << endl;
                    int sp = input.find_first_of(' ', 0);
                    string exist_list_name = input.substr(0, sp);
                    string append_list = input.substr(sp+1,input.size()-sp);
//                    cout << exist_list_name << " - " << list << endl; 
                    if (lists[exist_list_name] == NULL)
                        cout << "there is no list " << exist_list_name << endl;
                    else {
                        IntList *new_list = new IntList(*lists[exist_list_name]);
                        
                        string line = append_list.substr(1, append_list.size()-2);
//                        cout << line << endl;
                        int line_size = line.size();
                        std::string tmp = "";
                        tmp += line[0];
                        for(int i=1; i<line_size; i++){
                            if (line[i] == ' '){
                                int value = atoi(tmp.c_str());
                                //std::cout << "item:" << item << std::endl;
                                new_list->push(value);
                                tmp.clear();
                            }
                            else {
                                tmp += line[i];
                            }
                        }
                        new_list->push(atoi(tmp.c_str()));
                        
                        if (lists[list_name] != NULL) delete lists[list_name];
                        lists[list_name] = new_list;
                        cout << list_name << " = " << *new_list << endl;
                    }
                } else if (input[0]=='(') {
                    //получается что тупо присвоить список
                    //получаем список    
//                    input = input.substr(0, input.size()-1);
//                    std::cout << list_name << " - " << input << std::endl;
                    IntList *list = new IntList(input);
                    //вдруг раньше что-нибудь записано, так удаляем его нах
                    if (lists[list_name] != NULL) delete lists[list_name];
                    lists[list_name] = list;
                    cout << list_name << " = " << *list << endl;
                } 
            }
            //комманда вывода хвоста
            else if (input.substr(0,3) == "cdr") {
                string list_name = input.substr(4,input.size()-4);
                if (lists[list_name] == NULL)
                    cout << "there is no list " << list_name << endl;
                else {
                    cout << lists[list_name]->printTail() << endl;
                }
            }
        }
        else std::cout << "error" << std::endl;
    } while (input != "exit");
    
//    map<string, IntList*> list_map;
//    IntList *one = new IntList("(1 2 3)");
//    IntList *two = new IntList("(4 5 6)");
//    list_map["one"] = one;
//    list_map["two"] = two;
//    std::cout << *list_map["one"] << "\t" << *list_map["two"] << std::endl;
//    delete one;
//    delete two;
    
    return 0;
}