vector<string> fullJustify(vector<string>& words, int maxWidth) {
     vector<string> ans;
     int low = 0, high = 0, sz = words.size ();
     while (low < sz){
         int cnt = 0, num = 0; high = low;
         bool add = false;
         while (high < sz && words[high].length() + cnt + add<= maxWidth){
             cnt += words[high].length () + add; num++;high++;
             add = true;
         }
         string tmp(maxWidth, ' ');
         if (num == 1){
             copy_n (words[low].begin (), words[low].length (), tmp.begin());
         }
         else{
             int tot = maxWidth - cnt;
             int pre = tot / (num - 1);
             int left = tot - (num - 1) * pre;
             int idx = 0;
             for (int i=0;i<num;i++){
                 copy_n (words[low + i].begin(), words[low + i].length (), tmp.begin() + idx);
                 idx += words[low + i].length () + 1;
                 if (high == sz) continue;
                 idx += pre;
                 if (i < left)
                     idx++;
             }
         }
         ans.push_back (tmp);
         low = high;
     }
     return ans;
 }
int main(){

    int ints[] = {1, 2, 3, 4};
    double doubles[4] = {};
    copy_n(doubles, ints, 4);
    return 0;
}
Example #3
0
int main()
{
    char *d = "Hello World!";
    char *s, s_string[ MAXSIZE ];
    s = s_string;
    
    printf("%s\n", d );
    copy_n( d , s , 5 );
    printf("%s\n", s );
    copy_n( d , s , 10 );
    printf("%s\n", s );
    copy_n( d , s , 15 );
    printf("%s\n", s );

    return EXIT_SUCCESS;
}
Example #4
0
 void Map::sp_rev(bvec_t** arg, bvec_t** res, int* iw, bvec_t* w, int mem) const {
   int n_in = this->n_in(), n_out = this->n_out();
   bvec_t** arg1 = arg+n_in;
   copy_n(arg, n_in, arg1);
   bvec_t** res1 = res+n_out;
   copy_n(res, n_out, res1);
   for (int i=0; i<n_; ++i) {
     f_->sp_rev(arg1, res1, iw, w, 0);
     for (int j=0; j<n_in; ++j) {
       if (arg1[j]) arg1[j] += f_.nnz_in(j);
     }
     for (int j=0; j<n_out; ++j) {
       if (res1[j]) res1[j] += f_.nnz_out(j);
     }
   }
 }
Example #5
0
File: main.cpp Project: CCJY/coliru
int main()
{
    const char *str  = "hello world";
    const char *oops = "zzzzzzzzzzz";

    copy_n(str, 20, std::ostream_iterator<char>(std::cout));
}
Example #6
0
 void Map::evalGen(const T** arg, T** res, int* iw, T* w) const {
   int n_in = this->n_in(), n_out = this->n_out();
   const T** arg1 = arg+n_in;
   copy_n(arg, n_in, arg1);
   T** res1 = res+n_out;
   copy_n(res, n_out, res1);
   for (int i=0; i<n_; ++i) {
     f_(arg1, res1, iw, w, 0);
     for (int j=0; j<n_in; ++j) {
       if (arg1[j]) arg1[j] += f_.nnz_in(j);
     }
     for (int j=0; j<n_out; ++j) {
       if (res1[j]) res1[j] += f_.nnz_out(j);
     }
   }
 }
Example #7
0
/// Copies data from \p p, \p n to the linked block starting at \p start.
void memlink::copy (iterator start, const void* p, size_type n)
{
    assert (data() || !n);
    assert (p || !n);
    assert (start >= begin() && start + n <= end());
    if (p)
	copy_n (const_iterator(p), n, start);
}
Example #8
0
int main(void){
	char dst[100],src[100];
	int n;
	scanf("%s",&src);
	scanf("%d",&n);
	copy_n(dst,src,n);
	printf("%s\n", dst);
	return 1;
}
Example #9
0
/// Fills the linked block with the given pattern.
/// \arg start   Offset at which to start filling the linked block
/// \arg p       Pointer to the pattern.
/// \arg elSize  Size of the pattern.
/// \arg elCount Number of times to write the pattern.
/// Total number of bytes written is \p elSize * \p elCount.
///
void memlink::fill (iterator start, const void* p, size_type elSize, size_type elCount)
{
    assert (data() || !elCount || !elSize);
    assert (start >= begin() && start + elSize * elCount <= end());
    if (elSize == 1)
	fill_n (start, elCount, *reinterpret_cast<const uint8_t*>(p));
    else while (elCount--)
	start = copy_n (const_iterator(p), elSize, start);
}
Example #10
0
int main(void){
	char src[1000], dst[1001];
	int n;	
	printf("Please enter a string: ");
	fgets(src, 1000, stdin);
	printf("How many characters would you like to copy: ");
	scanf("%d", &n);
	printf("The result of copy_n() for %s is: %s\n", src, copy_n(dst, src, n));
	return 0;
}
Example #11
0
 std::tuple<I0, I1, O>
 operator()(I0 begin0, iterator_difference_t<I0> n0,
            I1 begin1, iterator_difference_t<I1> n1,
            O out, C r = C{}, P0 p0 = P0{}, P1 p1 = P1{}) const
 {
     using T = std::tuple<I0, I1, O>;
     auto &&ir = invokable(r);
     auto &&ip0 = invokable(p0);
     auto &&ip1 = invokable(p1);
     auto n0orig = n0;
     auto n1orig = n1;
     auto b0 = uncounted(begin0);
     auto b1 = uncounted(begin1);
     while(true)
     {
         if(0 == n0)
         {
             auto res = copy_n(b1, n1, out);
             begin0 = recounted(begin0, b0, n0orig);
             begin1 = recounted(begin1, res.first, n1orig);
             return T{begin0, begin1, res.second};
         }
         if(0 == n1)
         {
             auto res = copy_n(b0, n0, out);
             begin0 = recounted(begin0, res.first, n0orig);
             begin1 = recounted(begin1, b1, n1orig);
             return T{begin0, begin1, res.second};
         }
         if(ir(ip1(*b1), ip0(*b0)))
         {
             *out = *b1;
             ++b1; ++out; --n1;
         }
         else
         {
             *out = *b0;
             ++b0; ++out; --n0;
         }
     }
 }
Example #12
0
 int getFrames(int endIndex, int num, OutputIterator result) const {
     QReadLocker locker(&_lock);
     auto end = _history.rbegin();
     endIndex = std::min(_nextFrameNumber, endIndex);
     int numFromBack = _nextFrameNumber - endIndex;
     if (numFromBack >= _history.size()) {
         return 0;
     } else {
         advance(end, numFromBack);
         int startFrame = _nextFrameNumber - _history.size();
         int numToCopy = std::min(endIndex - 1 - startFrame, num);
         copy_n(end, numToCopy, result);
         return std::max(numToCopy, 0);
     }
 }
Example #13
0
inline void dispatch_reduce(InputIterator first,
                            InputIterator last,
                            OutputIterator result,
                            const plus<T> &function,
                            command_queue &queue)
{
    const context &context = queue.get_context();

    // reduce to temporary buffer on device
    array<T, 1> tmp(context);
    dispatch_reduce(first, last, tmp.begin(), function, queue);

    // copy to result iterator
    copy_n(tmp.begin(), 1, result, queue);
}
Example #14
0
/// \brief Reallocates internal block to hold at least \p newSize bytes.
///
/// Additional memory may be allocated, but for efficiency it is a very
/// good idea to call reserve before doing byte-by-byte edit operations.
/// The block size as returned by size() is not altered. reserve will not
/// reduce allocated memory. If you think you are wasting space, call
/// deallocate and start over. To avoid wasting space, use the block for
/// only one purpose, and try to get that purpose to use similar amounts
/// of memory on each iteration.
///
void memblock::reserve (size_type newSize, bool bExact)
{
    if ((newSize += minimumFreeCapacity()) <= m_Capacity)
	return;
    void* oldBlock (is_linked() ? NULL : data());
    if (!bExact)
    	newSize = Align (newSize, c_PageSize);
    pointer newBlock = (pointer) realloc (oldBlock, newSize);
	if (!newBlock)
		__THROW_BAD_ALLOC(newSize);
    if (!oldBlock && cdata())
	copy_n (cdata(), min (size() + 1, newSize), newBlock);
    link (newBlock, size());
    m_Capacity = newSize;
}
Example #15
0
int main(void)
{
    char dst[MAX_LEN] = { 0 };
    char src[MAX_LEN] = { 0 };
    int i = 0;

    fgets(src, MAX_LEN, stdin);
    copy_n(dst, src, MAX_LEN);

    while (dst[i] != NUL) {
        putchar(dst[i]);
        ++i;
    }

    return 0;
}
Example #16
0
/// \brief Reallocates internal block to hold at least \p newSize bytes.
///
/// Additional memory may be allocated, but for efficiency it is a very
/// good idea to call reserve before doing byte-by-byte edit operations.
/// The block size as returned by size() is not altered. reserve will not
/// reduce allocated memory. If you think you are wasting space, call
/// deallocate and start over. To avoid wasting space, use the block for
/// only one purpose, and try to get that purpose to use similar amounts
/// of memory on each iteration.
///
void memblock::reserve (size_type newSize, bool bExact)
{
    if ((newSize += minimumFreeCapacity()) <= m_Capacity)
	return;
    pointer oldBlock (is_linked() ? NULL : data());
    const size_t alignedSize (Align (newSize, 64));
    if (!bExact)
	newSize = alignedSize;
    pointer newBlock = (pointer) realloc (oldBlock, newSize);
    if (!newBlock)
	USTL_THROW(bad_alloc (newSize));
    if (!oldBlock & (cdata() != NULL))
	copy_n (cdata(), min (size() + 1, newSize), newBlock);
    link (newBlock, size());
    m_Capacity = newSize;
}
Example #17
0
inline OutputIterator serial_unique_copy(InputIterator first,
                                         InputIterator last,
                                         OutputIterator result,
                                         BinaryPredicate op,
                                         command_queue &queue)
{
    if(first == last){
        return result;
    }

    typedef typename std::iterator_traits<InputIterator>::value_type value_type;

    const context &context = queue.get_context();

    size_t count = detail::iterator_range_size(first, last);

    detail::meta_kernel k("serial_unique_copy");

    vector<uint_> unique_count_vector(1, context);

    size_t size_arg = k.add_arg<const uint_>("size");
    size_t unique_count_arg = k.add_arg<uint_ *>(memory_object::global_memory, "unique_count");

    k << k.decl<uint_>("index") << " = 0;\n"
      << k.decl<value_type>("current") << " = " << first[k.var<uint_>("0")] << ";\n"
      << result[k.var<uint_>("0")] << " = current;\n"
      << "for(uint i = 1; i < size; i++){\n"
      << "    " << k.decl<value_type>("next") << " = " << first[k.var<uint_>("i")] << ";\n"
      << "    if(!" << op(k.var<value_type>("current"), k.var<value_type>("next")) << "){\n"
      << "        " << result[k.var<uint_>("++index")] << " = next;\n"
      << "        " << "current = next;\n"
      << "    }\n"
      << "}\n"
      << "*unique_count = index + 1;\n";

    k.set_arg<const uint_>(size_arg, count);
    k.set_arg(unique_count_arg, unique_count_vector.get_buffer());

    k.exec_1d(queue, 0, 1, 1);

    uint_ unique_count;
    copy_n(unique_count_vector.begin(), 1, &unique_count, queue);

    return result + unique_count;
}
Example #18
0
/// \brief Reallocates internal block to hold at least \p newSize bytes.
///
/// Additional memory may be allocated, but for efficiency it is a very
/// good idea to call reserve before doing byte-by-byte edit operations.
/// The block size as returned by size() is not altered. reserve will not
/// reduce allocated memory. If you think you are wasting space, call
/// deallocate and start over. To avoid wasting space, use the block for
/// only one purpose, and try to get that purpose to use similar amounts
/// of memory on each iteration.
///
void memblock::reserve (size_type newSize, bool bExact)
{
    if ((newSize += minimumFreeCapacity()) <= m_Capacity)
	return;
    void* oldBlock (is_linked() ? NULL : data());
    if (!bExact)
	newSize = Align (newSize, c_PageSize);
    pointer newBlock = (pointer) realloc (oldBlock, newSize);
    if (!newBlock)
#if PLATFORM_ANDROID
        printf("bad_alloc\n");
#else
	throw bad_alloc (newSize);
#endif
    if (!oldBlock && cdata())
	copy_n (cdata(), min (size() + 1, newSize), newBlock);
    link (newBlock, size());
    m_Capacity = newSize;
}
inline void dispatch_reduce(InputIterator first,
                            InputIterator last,
                            OutputIterator result,
                            const plus<T> &function,
                            command_queue &queue)
{
    const context &context = queue.get_context();
    const device &device = queue.get_device();

    // reduce to temporary buffer on device
    array<T, 1> value(context);
    if(device.type() & device::cpu){
        detail::reduce_on_cpu(first, last, value.begin(), function, queue);
    }
    else {
        reduce_on_gpu(first, last, value.begin(), function, queue);
    }

    // copy to result iterator
    copy_n(value.begin(), 1, result, queue);
}
Example #20
0
//**********************************************************************************************
//******************************    Операция возведения в степень    ***************************        
        PolynomN6& PolynomN6::Pow(PolynomN6 &a, Integer &n)
        {
                if(n.isNegative())
			throw std::domain_error("Число n - отрицательное результат не определен");

                _modulePolynom = a._modulePolynom;
                _module=a._module;
                
                PolynomN6 copy_a(a);
		Integer copy_n(n);

		setOne();
                
		uint s = copy_n.getNumberBits();
		for(uint i=0;i<s;i++)
		{
                        Mul(*this, *this);
			if(copy_n.getBit(s-1-i))
			        Mul(*this, copy_a);
		}

                return *this;
        }
Example #21
0
 polynomial& operator=(const polynomial<T>& o)
 {
   vals = std::make_shared<std::vector<T>>(o.size());
   copy_n(&o(0),o.size(),&element(0));
   return *this;
 }
Example #22
0
  void Newton::solve(void* mem) const {
    auto m = static_cast<NewtonMemory*>(mem);

    // Get the initial guess
    casadi_copy(m->iarg[iin_], n_, m->x);

    // Perform the Newton iterations
    m->iter=0;
    bool success = true;
    while (true) {
      // Break if maximum number of iterations already reached
      if (m->iter >= max_iter_) {
        log("eval", "Max. iterations reached.");
        m->return_status = "max_iteration_reached";
        success = false;
        break;
      }

      // Start a new iteration
      m->iter++;

      // Use x to evaluate J
      copy_n(m->iarg, n_in(), m->arg);
      m->arg[iin_] = m->x;
      m->res[0] = m->jac;
      copy_n(m->ires, n_out(), m->res+1);
      m->res[1+iout_] = m->f;
      calc_function(m, "jac_f_z");

      // Check convergence
      double abstol = 0;
      if (abstol_ != numeric_limits<double>::infinity()) {
        for (int i=0; i<n_; ++i) {
          abstol = max(abstol, fabs(m->f[i]));
        }
        if (abstol <= abstol_) {
          casadi_msg("Converged to acceptable tolerance - abstol: " << abstol_);
          break;
        }
      }

      // Factorize the linear solver with J
      linsol_.factorize(m->jac);
      linsol_.solve(m->f, 1, false);

      // Check convergence again
      double abstolStep=0;
      if (numeric_limits<double>::infinity() != abstolStep_) {
        for (int i=0; i<n_; ++i) {
          abstolStep = max(abstolStep, fabs(m->f[i]));
        }
        if (abstolStep <= abstolStep_) {
          casadi_msg("Converged to acceptable tolerance - abstolStep: " << abstolStep_);
          break;
        }
      }

      if (print_iteration_) {
        // Only print iteration header once in a while
        if (m->iter % 10==0) {
          printIteration(userOut());
        }

        // Print iteration information
        printIteration(userOut(), m->iter, abstol, abstolStep);
      }

      // Update Xk+1 = Xk - J^(-1) F
      casadi_axpy(n_, -1., m->f, m->x);
    }

    // Get the solution
    casadi_copy(m->x, n_, m->ires[iout_]);

    // Store the iteration count
    if (success) m->return_status = "success";

    casadi_msg("Newton::solveNonLinear():end after " << m->iter << " steps");
  }
Example #23
0
static void TestAlgorithms (void)
{
    static const int c_TestNumbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 13, 14, 15, 16, 17, 18 };
    const int* first = c_TestNumbers;
    const int* last = first + VectorSize(c_TestNumbers);
    intvec_t v, buf;
    v.assign (first, last);
    PrintVector (v);

    cout << "swap(1,2)\n";
    swap (v[0], v[1]);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy(0,8,9)\n";
    copy (v.begin(), v.begin() + 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with back_inserter\n";
    v.clear();
    copy (first, last, back_inserter(v));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with inserter\n";
    v.clear();
    copy (first, first + 5, inserter(v, v.begin()));
    copy (first, first + 5, inserter(v, v.begin() + 3));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_n(0,8,9)\n";
    copy_n (v.begin(), 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_if(is_even)\n";
    intvec_t v_even;
    copy_if (v, back_inserter(v_even), &is_even);
    PrintVector (v_even);
    v.assign (first, last);

    cout << "for_each(printint)\n{ ";
    for_each (v, &printint);
    cout << "}\n";

    cout << "for_each(reverse_iterator, printint)\n{ ";
    for_each (v.rbegin(), v.rend(), &printint);
    cout << "}\n";

    cout << "find(10)\n";
    cout.format ("10 found at offset %zd\n", abs_distance (v.begin(), find (v, 10)));

    cout << "count(13)\n";
    cout.format ("%zu values of 13, %zu values of 18\n", count(v,13), count(v,18));

    cout << "transform(sqr)\n";
    transform (v, &sqr);
    PrintVector (v);
    v.assign (first, last);

    cout << "replace(13,666)\n";
    replace (v, 13, 666);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill(13)\n";
    fill (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill_n(5, 13)\n";
    fill_n (v.begin(), 5, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill 64083 uint8_t(0x41) ";
    TestBigFill<uint8_t> (64083, 0x41);
    cout << "fill 64083 uint16_t(0x4142) ";
    TestBigFill<uint16_t> (64083, 0x4142);
    cout << "fill 64083 uint32_t(0x41424344) ";
    TestBigFill<uint32_t> (64083, 0x41424344);
    cout << "fill 64083 float(0.4242) ";
    TestBigFill<float> (64083, 0x4242f);
#if HAVE_INT64_T
    cout << "fill 64083 uint64_t(0x4142434445464748) ";
    TestBigFill<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "copy 64083 uint8_t(0x41) ";
    TestBigCopy<uint8_t> (64083, 0x41);
    cout << "copy 64083 uint16_t(0x4142) ";
    TestBigCopy<uint16_t> (64083, 0x4142);
    cout << "copy 64083 uint32_t(0x41424344) ";
    TestBigCopy<uint32_t> (64083, 0x41424344);
    cout << "copy 64083 float(0.4242) ";
    TestBigCopy<float> (64083, 0.4242f);
#if HAVE_INT64_T
    cout << "copy 64083 uint64_t(0x4142434445464748) ";
    TestBigCopy<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "generate(genint)\n";
    generate (v, &genint);
    PrintVector (v);
    v.assign (first, last);

    cout << "rotate(4)\n";
    rotate (v, 7);
    rotate (v, -3);
    PrintVector (v);
    v.assign (first, last);

    cout << "merge with (3,5,10,11,11,14)\n";
    const int c_MergeWith[] = { 3,5,10,11,11,14 };
    intvec_t vmerged;
    merge (v.begin(), v.end(), VectorRange(c_MergeWith), back_inserter(vmerged));
    PrintVector (vmerged);
    v.assign (first, last);

    cout << "inplace_merge with (3,5,10,11,11,14)\n";
    v.insert (v.end(), VectorRange(c_MergeWith));
    inplace_merge (v.begin(), v.end() - VectorSize(c_MergeWith), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "remove(13)\n";
    remove (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "remove (elements 3, 4, 6, 15, and 45)\n";
    vector<uoff_t> toRemove;
    toRemove.push_back (3);
    toRemove.push_back (4);
    toRemove.push_back (6);
    toRemove.push_back (15);
    toRemove.push_back (45);
    typedef index_iterate<intvec_t::iterator, vector<uoff_t>::iterator> riiter_t;
    riiter_t rfirst = index_iterator (v.begin(), toRemove.begin());
    riiter_t rlast = index_iterator (v.begin(), toRemove.end());
    remove (v, rfirst, rlast);
    PrintVector (v);
    v.assign (first, last);

    cout << "unique\n";
    unique (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "reverse\n";
    reverse (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "lower_bound(10)\n";
    PrintVector (v);
    cout.format ("10 begins at position %zd\n", abs_distance (v.begin(), lower_bound (v, 10)));
    v.assign (first, last);

    cout << "upper_bound(10)\n";
    PrintVector (v);
    cout.format ("10 ends at position %zd\n", abs_distance (v.begin(), upper_bound (v, 10)));
    v.assign (first, last);

    cout << "equal_range(10)\n";
    PrintVector (v);
    TestEqualRange (v);
    v.assign (first, last);

    cout << "sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    stable_sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "is_sorted\n";
    random_shuffle (v);
    const bool bNotSorted = is_sorted (v.begin(), v.end());
    sort (v);
    const bool bSorted = is_sorted (v.begin(), v.end());
    cout << "unsorted=" << bNotSorted << ", sorted=" << bSorted << endl;
    v.assign (first, last);

    cout << "find_first_of\n";
    static const int c_FFO[] = { 10000, -34, 14, 27 };
    cout.format ("found 14 at position %zd\n", abs_distance (v.begin(), find_first_of (v.begin(), v.end(), VectorRange(c_FFO))));
    v.assign (first, last);

    static const int LC1[] = { 3, 1, 4, 1, 5, 9, 3 };
    static const int LC2[] = { 3, 1, 4, 2, 8, 5, 7 };
    static const int LC3[] = { 1, 2, 3, 4 };
    static const int LC4[] = { 1, 2, 3, 4, 5 };
    cout << "lexicographical_compare";
    cout << "\nLC1 < LC2 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC2));
    cout << "\nLC2 < LC2 == " << lexicographical_compare (VectorRange(LC2), VectorRange(LC2));
    cout << "\nLC3 < LC4 == " << lexicographical_compare (VectorRange(LC3), VectorRange(LC4));
    cout << "\nLC4 < LC1 == " << lexicographical_compare (VectorRange(LC4), VectorRange(LC1));
    cout << "\nLC1 < LC4 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC4));

    cout << "\nmax_element\n";
    cout.format ("max element is %d\n", *max_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "min_element\n";
    cout.format ("min element is %d\n", *min_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "partial_sort\n";
    reverse (v);
    partial_sort (v.begin(), v.iat(v.size() / 2), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "partial_sort_copy\n";
    reverse (v);
    buf.resize (v.size());
    partial_sort_copy (v.begin(), v.end(), buf.begin(), buf.end());
    PrintVector (buf);
    v.assign (first, last);

    cout << "partition\n";
    partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_partition\n";
    stable_partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "next_permutation\n";
    buf.resize (3);
    iota (buf.begin(), buf.end(), 1);
    PrintVector (buf);
    while (next_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    cout << "prev_permutation\n";
    reverse (buf);
    PrintVector (buf);
    while (prev_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    v.assign (first, last);

    cout << "reverse_copy\n";
    buf.resize (v.size());
    reverse_copy (v.begin(), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    cout << "rotate_copy\n";
    buf.resize (v.size());
    rotate_copy (v.begin(), v.iat (v.size() / 3), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    static const int c_Search1[] = { 5, 6, 7, 8, 9 }, c_Search2[] = { 10, 10, 11, 14 };
    cout << "search\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "find_end\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "search_n\n";
    cout.format ("{14} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 1, 14)));
    cout.format ("{13,13} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 2, 13)));
    cout.format ("{10,10,10} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 3, 10)));
    v.assign (first, last);

    cout << "includes\n";
    static const int c_Includes[] = { 5, 14, 15, 18, 20 };
    cout << "includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes)-1);
    cout << ", not includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes));
    cout << endl;

    static const int c_Set1[] = { 1, 2, 3, 4, 5, 6 }, c_Set2[] = { 4, 4, 6, 7, 8 };
    intvec_t::iterator setEnd;
    cout << "set_difference\n";
    v.resize (4);
    setEnd = set_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_symmetric_difference\n";
    v.resize (7);
    setEnd = set_symmetric_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_intersection\n";
    v.resize (2);
    setEnd = set_intersection (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_union\n";
    v.resize (9);
    setEnd = set_union (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    v.assign (first, last);
}
TPolyhedron CopyPolyhedron (const TPolyhedron& ph) {
	TPolyhedron newph = ph;
	newph.vertices = new TVector3[ph.num_vertices];
	copy_n(ph.vertices, ph.num_vertices, newph.vertices); // XXX
	return newph;
}
Example #25
0
  void QpToNlp::
  eval(void* mem, const double** arg, double** res, int* iw, double* w) const {
    // Inputs
    const double *h_, *g_, *a_, *lba_, *uba_, *lbx_, *ubx_, *x0_;
    // Outputs
    double *x_, *f_, *lam_a_, *lam_x_;

    // Get input pointers
    h_ = arg[QPSOL_H];
    g_ = arg[QPSOL_G];
    a_ = arg[QPSOL_A];
    lba_ = arg[QPSOL_LBA];
    uba_ = arg[QPSOL_UBA];
    lbx_ = arg[QPSOL_LBX];
    ubx_ = arg[QPSOL_UBX];
    x0_ = arg[QPSOL_X0];

    // Get output pointers
    x_ = res[QPSOL_X];
    f_ = res[QPSOL_COST];
    lam_a_ = res[QPSOL_LAM_A];
    lam_x_ = res[QPSOL_LAM_X];

    // Buffers for calling the NLP solver
    const double** arg1 = arg + n_in();
    double** res1 = res + n_out();
    fill_n(arg1, static_cast<int>(NLPSOL_NUM_IN), nullptr);
    fill_n(res1, static_cast<int>(NLPSOL_NUM_OUT), nullptr);

    // NLP inputs
    arg1[NLPSOL_X0] = x0_;
    arg1[NLPSOL_LBG] = lba_;
    arg1[NLPSOL_UBG] = uba_;
    arg1[NLPSOL_LBX] = lbx_;
    arg1[NLPSOL_UBX] = ubx_;

    // NLP parameters
    arg1[NLPSOL_P] = w;

    // Quadratic term
    int nh = nnz_in(QPSOL_H);
    if (h_) {
      copy_n(h_, nh, w);
    } else {
      fill_n(w, nh, 0);
    }
    w += nh;

    // Linear objective term
    int ng = nnz_in(QPSOL_G);
    if (g_) {
      copy_n(g_, ng, w);
    } else {
      fill_n(w, ng, 0);
    }
    w += ng;

    // Linear constraints
    int na = nnz_in(QPSOL_A);
    if (a_) {
      copy_n(a_, na, w);
    } else {
      fill_n(w, na, 0);
    }
    w += na;

    // Solution
    res1[NLPSOL_X] = x_;
    res1[NLPSOL_F] = f_;
    res1[NLPSOL_LAM_X] = lam_x_;
    res1[NLPSOL_LAM_G] = lam_a_;

    // Solve the NLP
    solver_(arg1, res1, iw, w, 0);
  }
Example #26
0
  int Switch::eval_sx(const SXElem** arg, SXElem** res,
      casadi_int* iw, SXElem* w, void* mem) const {
    // Input and output buffers
    const SXElem** arg1 = arg + n_in_;
    SXElem** res1 = res + n_out_;

    // Extra memory needed for chaining if_else calls
    std::vector<SXElem> w_extra(nnz_out());
    std::vector<SXElem*> res_tempv(n_out_);
    SXElem** res_temp = get_ptr(res_tempv);

    for (casadi_int k=0; k<f_.size()+1; ++k) {

      // Local work vector
      SXElem* wl = w;

      // Local work vector
      SXElem* wll = get_ptr(w_extra);

      if (k==0) {
        // For the default case, redirect the temporary results to res
        copy_n(res, n_out_, res_temp);
      } else {
        // For the other cases, store the temporary results
        for (casadi_int i=0; i<n_out_; ++i) {
          res_temp[i] = wll;
          wll += nnz_out(i);
        }
      }

      copy_n(arg+1, n_in_-1, arg1);
      copy_n(res_temp, n_out_, res1);

      const Function& fk = k==0 ? f_def_ : f_[k-1];

      // Project arguments with different sparsity
      for (casadi_int i=0; i<n_in_-1; ++i) {
        if (arg1[i]) {
          const Sparsity& f_sp = fk.sparsity_in(i);
          const Sparsity& sp = sparsity_in_[i+1];
          if (f_sp!=sp) {
            SXElem *t = wl; wl += f_sp.nnz(); // t is non-const
            casadi_project(arg1[i], sp, t, f_sp, wl);
            arg1[i] = t;
          }
        }
      }

      // Temporary memory for results with different sparsity
      for (casadi_int i=0; i<n_out_; ++i) {
        if (res1[i]) {
          const Sparsity& f_sp = fk.sparsity_out(i);
          const Sparsity& sp = sparsity_out_[i];
          if (f_sp!=sp) { res1[i] = wl; wl += f_sp.nnz();}
        }
      }

      // Evaluate the corresponding function
      if (fk(arg1, res1, iw, wl, 0)) return 1;

      // Project results with different sparsity
      for (casadi_int i=0; i<n_out_; ++i) {
        if (res1[i]) {
          const Sparsity& f_sp = fk.sparsity_out(i);
          const Sparsity& sp = sparsity_out_[i];
          if (f_sp!=sp) casadi_project(res1[i], f_sp, res_temp[i], sp, wl);
        }
      }

      if (k>0) { // output the temporary results via an if_else
        SXElem cond = k-1==arg[0][0];
        for (casadi_int i=0; i<n_out_; ++i) {
          if (res[i]) {
            for (casadi_int j=0; j<nnz_out(i); ++j) {
              res[i][j] = if_else(cond, res_temp[i][j], res[i][j]);
            }
          }
        }
      }

    }
    return 0;
  }