int main()
{
    // display header message
    cout << "***************************************************************\n"
            "*** This program computes quartiles given a list of numbers ***\n"
            "***************************************************************\n";
    cout << endl;

    // ask for a list of numbers and store the list as a vector
    cout << "Enter all a list of numbers: ";
    vector<double> v;
    double x;
    while (cin >> x)
        v.push_back(x);

    // check vector size and action accordingly
    cout << endl;
    typedef vector<double>::size_type vecSize;
    vecSize N = v.size();
    if (N ==0 )
    {
        cout << "You must enter some numbers! " << endl;
        return 1;
    }

    else if (N ==1 )
    {
        cout << " Only 1 number supplied. Q1, Q2, and Q3 all equate to " << v[0] << endl;
        return 0;
    }

    else
    {
        // sort the homework grades;
        sort(v.begin(),v.end());

        // declare new variables
        vecSize NMod4 = (N % 4);  // identification of 1 of the 4 known datum distribution profiles
        string datumDistr = "";   // datum distribution profile
        vecSize M, ML, MU;        // core vector indices for quartile computation
        double m, ml, mu;         // quartile values are store here

        // compute quartiles for the 4 known patterns
        if ( NMod4 == 0 )
        {
            // Q1-Q3 datum distribution: [0 0 0]
            datumDistr = "[0 0 0]";
            M = N / 2;
            ML = M / 2;
            MU = M + ML;

            // grab quartile values
            ml= (v[ML] + v[ML-1]) / 2;     // datum: 0
            m = (v[M] + v[M-1]) / 2;       // datum: 0
            mu = (v[MU] + v[MU-1]) / 2;    // datum: 0
        }

        else if ( NMod4 == 1 )
        {
            // Q1-Q3 datum distribution: [0 1 0]
            datumDistr = "[0 1 0]";
            M = N / 2;
            ML = M / 2;
            MU = M + ML + 1;

            // grab quartile values
            datumDistr = "[0 0 0]";
            ml= (v[ML] + v[ML-1]) / 2;      // datum: 0
            m = v[M];                       // datum: 1
            mu = (v[MU] + v[MU-1]) / 2;     // datum: 0
        }

        else if ( NMod4 == 2 )
        {
            // Q1-Q3 datum distribution: [1 0 1]
            datumDistr = "[1 0 1]";
            M = N / 2;
            ML = M / 2;
            MU = M + ML;

            // grab quartile values
            ml= v[ML];                    // datum: 1
            m = (v[M] + v[M-1]) / 2;     // datum: 0
            mu = v[MU];                   // datum: 1
        }

        else if ( NMod4 == 3 )
        {
            // Q1-Q3 datum distribution: [1 1 1]
            datumDistr = "[1 1 1]";
            M = N / 2;
            ML = M / 2;
            MU = M + ML + 1;

            // grab quartile values
            ml= v[ML];                    // datum: 1
            m = v[M];                     // datum: 0
            mu = v[MU];                   // datum: 1
        }

        else
        {
            cout << "Unknown pattern discovered - new algorithm may be required.";
        }

        // Display results
        streamsize prec = cout.precision();
        cout << "Display the sorted (non-descending) vector below." << endl;
        cout << "Index: Number" << endl;
        for (vecSize i = 0; i !=  N; ++i)
        {
            cout << i << ": " << v[i] << endl;
        }
        cout << endl;
        cout << "Vector size: " << N << endl;
        cout << "Datum Distribution: " << datumDistr << endl;
        cout << setprecision(3) << endl
        << " Q1: " << ml << endl
        << " Q2: " << m << endl
        << " Q3: " << mu << endl
        << setprecision(prec);
    }
}
Example #2
0
void updateUniverse(int ignored_value){
	lastFrameTime = currentFrameTime;
	currentFrameTime = getCurrentTime();
	TIMESTEP = (currentFrameTime - lastFrameTime).total_milliseconds();
	if(program_state == STATE_SHOW_PLAYER_DEATH){
		deathCameraAngle += dDeathCameraAngle*TIMESTEP;
		deathPos += dDeathPos*TIMESTEP;
	}
	//detect collisions, add emitters to local containers
	vector<int> to_delete;
	for(unsigned int i=0;i<objectList.size();i++){
		for(unsigned int j=i+1;j<objectList.size();j++){
			if(objectList[i]->collision(objectList[j]) || objectList[j]->collision(objectList[i])){
				objectList[i]->notifyCollision();
				objectList[j]->notifyCollision();
				to_delete.push_back(i);
				to_delete.push_back(j);
			}
		}
	}
	sort(to_delete.begin(),to_delete.end());
	reverse(to_delete.begin(),to_delete.end());

	//erase the items marked for deletion
	vector<NewtonObject*> new_emitters;
	sem_wait(&obj_sem);
	for(unsigned int k=0;k<to_delete.size();k++){
		if(k+1 < to_delete.size() && to_delete[k] == to_delete[k+1]){
			continue; //don't want to multiply delete items
		} else {
			unsigned int i = to_delete[k];
			assert(objectList[i]->deleteMe()); //just checking ;)
			if(objectList[i] == player){
				program_state = STATE_SHOW_PLAYER_DEATH;
				deathPos = player->getPos();
				dDeathPos = player->getDPos();
				deathRot = player->getRot();
				deathCameraAngle = 2.356;
				player = NULL;
				target = NULL;
			} else if(objectList[i] == target){
				moveTarget(1);
				if(objectList[i] == target){ //...still
					//i.e. this is the only legitimate target
					target = NULL;
				}
			}

			Emitter* temp1 = new Emitter();
			temp1->setPos(objectList[i]->getPos());
			temp1->setDPos(objectList[i]->getDPos());
			temp1->setPDPos(Quaternion(1,0,0,0),3.141,0.002,0.00005);
			//temp1->setPDPos(Quaternion(1,0,0,0),0.1,0.02,0);
			temp1->setPLife(50, 49);
			temp1->setELife(35);
			temp1->setFlow(50,15);
			temp1->setColour(Vector(0.9,0.9,0.9),Vector(0.2,0.2,0.2),Vector(0.8,0.2,0.2),Vector(0.1,0.1,0.1));
			new_emitters.push_back((NewtonObject*) temp1);
			delete objectList[i];
			//GOTCHA: this line depends on to_delete being sorted in descending order
			objectList.erase(objectList.begin()+i);
		} //if not the same as the next object in to_delete
	} //end for
	sem_post(&obj_sem);

	for(unsigned int i=0;i<objectList.size();i++){
		objectList[i]->update(objectList);
	}
	//any objects which have been requested to be added last tick
	copy(newObjects.begin(),newObjects.end(),back_inserter(objectList));
	newObjects.clear();
	//any emitters just added
	copy(new_emitters.begin(),new_emitters.end(),back_inserter(objectList));

	glutPostRedisplay();
	glutTimerFunc(1,updateUniverse,0);
}
Example #3
0
int main()
{
   string s;
   ifstream in("input.txt");
   
   

   string_vector permutation_index;

   string::size_type left_col_width = 0;

   while (getline(in, s))
   {
      string_vector words = split(s);
      string_vector_size words_size = words.size();

      words[words_size - 1] += "|";

      string::size_type current_width = 0;

      for (string_vector_size i = 0; i != words_size; i++)
      {
         if (i != words_size - 1) current_width += words[i].size();

         string cyclic_string = "";
         for (string_vector_size j = i; j != words_size + i; j++)
         {
            cyclic_string += words[j % words_size] + " ";
         }
         permutation_index.push_back(cyclic_string.substr(0, cyclic_string.size() - 1));
      }

      if (current_width + words.size() - 2 > left_col_width) left_col_width = current_width + words.size() - 2;
   }

   sort(permutation_index.begin(), permutation_index.end());

   for (string_vector_size i = 0; i != permutation_index.size(); i++)
   {
      s = permutation_index[i];
      string_size delimetr_index = find(s, '|');
      string_size real_string_size = s.size() - 1;
      string delimetr = "\t";


      if (delimetr_index == real_string_size)
      {
         cout << string(left_col_width, ' ') << delimetr << s.substr(0, delimetr_index) << endl;
      }
      else if (left_col_width + delimetr_index == real_string_size - 1)
      {
         cout << s.substr(delimetr_index + 2, real_string_size - delimetr_index)
              << delimetr << s.substr(0, delimetr_index) << endl;
      }
      else
      {
         cout << string(left_col_width + delimetr_index - real_string_size + 1, ' ')
              << s.substr(delimetr_index + 2, real_string_size - delimetr_index)
              << delimetr << s.substr(0, delimetr_index) << endl;
      }
   }

   return 0;
}
bool general_partition::consistency_check()  {
    bool failed = false;

    //counting the real number of atoms by the labels
    vector<label_t> temp(labels);
    sort(temp.begin(),temp.end());
    entropy_pair entropie = ordered_vector_entropy(temp.data(),N);
    int n_calculated = entropie.second;
    double H = entropie.first;
    if(n!=n_calculated){
        printf("Number of atoms is wrong, is %d, should be %d\n",n,n_calculated);
        failed = true;
    }
    if(abs(H-entropia_shannon)>1e-9){
        printf("Entropy is wrong, is %.5f, should be %.5f\n",H,entropia_shannon);
        failed=true;
    }

    //atoms & labels
    for (label_t atom_label1 = 0; atom_label1 < n; atom_label1++) {
        for (Iter_t ii = reverse_iterator(atomi[atom_label1].end, & prev_site[0]); ii != end(); ii++) {
            if(*ii >= N){
                printf("Iterator is wrong, returned next site %d\n",*ii);
                print_array(&prev_site[0], N, "prev_s");
                failed = true;
                break;
            }
            if (labels[*ii] != atom_label1) {
                printf("Self consistency, backward iterator check 1 failed: %d instead of %d, at %d\n", labels[*ii], atom_label1, *ii);
                printf("Atom %d, from %d to %d\n",atom_label1,atomi[atom_label1].start,atomi[atom_label1].end);
                failed = true;
                break;
            }
        }
    }
    //checking that by the iterators, all the partition can be covered
    int count = 0;
    for (label_t atom_label1 = 0; atom_label1 < n; atom_label1++)
        for (Iter_t ii = reverse_iterator(atomi[atom_label1].end, & prev_site[0]); ii != end(); ii++)
            count++;
    if (count != N) {
        printf("Self consistency, backward iterator check 2 failed: count is %d (/%d)\n", count, N);
        for (label_t atom_label1 = 0; atom_label1 < n; atom_label1++)
        printf("Atom %d, from %d to %d\n",atom_label1,atomi[atom_label1].start,atomi[atom_label1].end);
        failed = true;
    }

    generate_forward_linking();

    //checking that the end and start of every atom are well set
    for (label_t atom_label1 = 0; atom_label1 < n; atom_label1++) {
        int inizio = atomi[atom_label1].start;
        if(inizio !=  prev_site[inizio]){
            printf("[%2d] should begin at %d, begins at %d\n",atom_label1,inizio,prev_site[inizio]);
            failed=true;
        }
        int finish = atomi[atom_label1].end;
        if(finish !=  next_site[finish]){
            printf("[%2d] should end at %d, ends at %d\n",atom_label1,finish,next_site[finish]);
            failed=true;
        }
    }
    //operators <= and == check
    bool uguale =  *this == *this;
    bool minore_uguale = *this <= *this;
    if(!uguale || !minore_uguale){
        printf("Failed equality test: == %d, <= %d\n",uguale,minore_uguale);
        failed = true;
    }

    //print summary of the partition
    if (failed) {
        label_t quanto = std::min(N, (label_t) 50);
        printf("n: %d\n", n);
        print_array(&labels[0], quanto, "labels");
        print_array(&prev_site[0], quanto, "prev_s");
        print_array(&next_site[0], quanto, "next_s");
    }
    return failed;
}
Example #5
0
//牌组排序(按照点数大小升序排列: 3,4,5...J,Q,K,A,2,SG,BG)
void CardCombine::combineSort()
{
    sort(_list.begin(),_list.end());
}
void Population::sortByFitness()
{
    sort(individuals.begin(), individuals.end(), compFitness);
}
Example #7
0
void CalcAirlight(IplImage *darkchannel, IplImage *input, double A[])
{
	int height = input->height;
	int width = input->width;
	int widthstep = input->widthStep;
	int gwidthstep = darkchannel->widthStep;
	int nch = input->nChannels;

	struct Pixel *v_darkchannel = (struct Pixel *)malloc(sizeof(struct Pixel) * height * width);
	int count = 0;
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < width; j++)
		{
			int value = *(uchar *)(darkchannel->imageData + i * gwidthstep + j);
			struct Pixel p = { value, i, j };
			v_darkchannel[count++] = p;
		}
	}
	sort(v_darkchannel, v_darkchannel + count, [](struct Pixel &a, struct Pixel &b){ return a.value > b.value; });

	IplImage *mask = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
	cvZero(mask);

	for (int i = 0; i < count * 0.001; i++)
	{
		struct Pixel p = v_darkchannel[i];
		*(uchar *)(mask->imageData + p.i * gwidthstep + p.j) = 255;
	}
	

	for (int k = 0; k < 3; k++)
	{
		struct Pixel *v_channel = (struct Pixel *)malloc(sizeof(struct Pixel) * height * width);
		int count = 0;

		for (int i = 0; i < height; i++)
		{
			for (int j = 0; j < width; j++)
			{
				int flag = *(uchar *)(mask->imageData + i * gwidthstep + j);
				if (flag == 0)
					continue;

				int value = *(uchar *)(input->imageData + i * widthstep + j * nch + k);
				struct Pixel p = { value, i, j };
				v_channel[count++] = p;
			}
		}

		sort(v_channel, v_channel + count, [](struct Pixel &a, struct Pixel &b){ return a.value > b.value; });
		
		double channel_airlight = 0;
		for (int i = 0; i < count * 0.01; i++)
		{
			channel_airlight += v_channel[i].value;
		}
		channel_airlight = channel_airlight / (count * 0.01);
		A[k] = channel_airlight;

		free(v_channel);
	}
	free(v_darkchannel);
}
Example #8
0
void IMGArchive::readHeader()
{
    istream* stream = dirStream;

#ifdef GTAFORMATS_LITTLE_ENDIAN
    StreamReader reader(stream);
#else
    EndianSwappingStreamReader reader(stream);
#endif

    int32_t firstBytes;

    stream->read((char*) &firstBytes, 4);
    streamoff gcount = stream->gcount();

    if (stream->eof()) {
        if (gcount == 0) {
            // This is an empty file: VER1 DIR files can be completely empty, so we assume this one is
            // such a file.

            version = VER1;
            return;
        } else {
            throw IMGException("Premature end of file", __FILE__, __LINE__);
        }
    }

    char* fourCC = (char*) &firstBytes;

    vector<IMGEntry*> entryVector;

    if (fourCC[0] == 'V'  &&  fourCC[1] == 'E'  &&  fourCC[2] == 'R'  &&  fourCC[3] == '2') {
        version = VER2;
        int32_t numEntries = reader.readU32();

        for (int32_t i = 0 ; i < numEntries ; i++) {
            IMGEntry* entry = new IMGEntry;
            stream->read((char*) entry, sizeof(IMGEntry));

#ifndef GTAFORMATS_LITTLE_ENDIAN
            entry->offset = SwapEndianness32(entry->offset);
            entry->size = SwapEndianness32(entry->size);
#endif

            entryVector.push_back(entry);
        }
    } else {
        version = VER1;

        // In VER1 'firstBytes' is actually part of the first entry, so we have to handle it manually.
        IMGEntry* firstEntry = new IMGEntry;

        firstEntry->offset = ToLittleEndian32(firstBytes);

        stream->read(((char*) firstEntry)+4, sizeof(IMGEntry)-4);

#ifndef GTAFORMATS_LITTLE_ENDIAN
        firstEntry->size = SwapEndianness32(firstEntry->size);
#endif

        entryVector.push_back(firstEntry);

        while (!stream->eof()) {
            IMGEntry* entry = new IMGEntry;
            stream->read((char*) entry, sizeof(IMGEntry));

#ifndef GTAFORMATS_LITTLE_ENDIAN
            entry->offset = SwapEndianness32(entry->offset);
            entry->size = SwapEndianness32(entry->size);
#endif

            streamoff lrc = stream->gcount();

            if (lrc != sizeof(IMGEntry)) {
                if (lrc == 0) {
                    delete entry;
                    break;
                } else {
                    char errmsg[128];
                    sprintf(errmsg, "ERROR: Input isn't divided into %u-byte blocks. Is this really a "
                            "VER1 DIR file?", (unsigned int) sizeof(IMGEntry));
                    throw IMGException(errmsg, __FILE__, __LINE__);
                }
            }

            entryVector.push_back(entry);
        }
    }

    // TODO: All IMG files I've seen so far are already sorted by offset, but I'm not sure if this is
    // always true, so we don't take any risks here...
    sort(entryVector.begin(), entryVector.end(), _EntrySortComparator);
    entries = EntryList(entryVector.begin(), entryVector.end());

    for (EntryIterator it = entries.begin() ; it != entries.end() ; it++) {
        IMGEntry* entry = *it;
        char* lname = new char[24];
        strtolower(lname, entry->name);
        string slname = lname;
        delete[] lname;
        entryMap.insert(pair<string, EntryIterator>(slname, it));
    }

    if (entries.size() > 0) {
        headerReservedSpace = (*entries.begin())->offset;
    } else {
        headerReservedSpace = 1;
    }
}
int main() {
    cout << "\n***************************************\n"
            "*** This program computes quartiles ***\n"
            "***************************************\n";
    cout << endl;


    //list to hold the numbers
    vector<int> v;
    int inputNumber;
    cout << "Enter your list of numbers: ";
    while(cin >> inputNumber) {
        v.push_back(inputNumber);
    }
    cout << endl;

    // create the size type and use it to define length of vector
    typedef vector<int>::size_type vSize;
    vSize length = v.size();
    vSize medianIndex, lowerIndex, upperIndex;
    double median = 0;
    double lower = 0;
    double upper = 0;

    if(length == 0)
    {
        cout << "You must enter some numbers! ";
        return 1;
    }
    else
    {
        sort(v.begin(), v.end());

        if (length % 4 == 0) //case [0 0 0]
        {
            medianIndex = length / 2;
            lowerIndex = medianIndex / 2;
            upperIndex = medianIndex + lowerIndex;

            median = (v[medianIndex] + v[medianIndex - 1]) / 2;
            lower = (v[lowerIndex] + v[lowerIndex - 1]) / 2;
            upper = (v[upperIndex] + v[upperIndex - 1]) / 2;
        }
        else if (length % 4 == 1) //case [0 1 0]
        {
            medianIndex = length / 2;
            lowerIndex = medianIndex / 2;
            upperIndex = medianIndex + lowerIndex + 1;

            median = v[medianIndex];
            lower = (v[lowerIndex] + v[lowerIndex - 1]) / 2;
            upper = (v[upperIndex] + v[upperIndex - 1]) / 2;
        }
        else if (length % 4 == 2) // case [1 0 1]
        {
            medianIndex = length / 2;
            lowerIndex = medianIndex / 2;
            upperIndex = medianIndex + lowerIndex;

            median = (v[medianIndex] + v[medianIndex - 1]) / 2;
            lower = v[lowerIndex];
            upper = v[upperIndex];
        }
        else if (length % 4 == 3) // case [1 1 1]
        {
            medianIndex = length / 2;
            lowerIndex = medianIndex / 2;
            upperIndex = medianIndex + lowerIndex + 1;

            median = v[medianIndex];
            lower = v[lowerIndex];
            upper = v[upperIndex];
        }
    }

    // print the results
    cout << "First quartile: " << lower
         << "\nMedian: " << median
         << "\nThird Quartile: " << upper;

    return 0;
}
Example #10
0
Foo Foo::sorted() &&
{
	cout << "sorted() && called." << endl;
	sort(data.begin(), data.end());
	return *this;
}
Example #11
0
int main()
{
	freopen("t.in", "r", stdin);
	Build(1, 0, UPPERLIM);
	Change(1, 0, UPPERLIM, 0, UPPERLIM, 0);
	while(! feof(stdin))
	{
		char cmd, ch_a, ch_b;
		int a, b;
		scanf("%c %c%d,%d%c\n", &cmd, &ch_a, &a, &b, &ch_b);
		if(ch_a == '[') a = a * 2;
		else a = a * 2 + 1;
		if(ch_b == ']') b = b * 2;
		else b = b * 2 - 1;
		switch(cmd)
		{
			case 'U': 
				Change(1, 0, UPPERLIM, a, b, 1);
				break;
			case 'I':
				if(a > 0)
					Change(1, 0, UPPERLIM, 0, a - 1, 0);
				if(b < UPPERLIM)
					Change(1, 0, UPPERLIM, b + 1, UPPERLIM, 0);
				break;
			case 'C':
				if(a > 0)
					Change(1, 0, UPPERLIM, 0, a - 1, 0);
				if(b < UPPERLIM)
					Change(1, 0, UPPERLIM, b + 1, UPPERLIM, 0);
				Change(1, 0, UPPERLIM, a, b, 2);
				break;
			case 'D':
				Change(1, 0, UPPERLIM, a, b, 0);
				break;
			case 'S':
				Change(1, 0, UPPERLIM, a, b, 2);
				break;
		}
	}
	Push_All(1, 0, UPPERLIM);
	for(int i = UPPERLIM + 1; i <= 2 * UPPERLIM + 1; i ++)
	{
		if(node[i].val == 1)
		{
			int j = i;
			while(node[j + 1].val == 1) j ++;
			interval[++ interval_num].st = i - UPPERLIM - 1;
			interval[interval_num].en = j - UPPERLIM - 1;
			i = j;
		}
	}
	if(interval_num == 0)
		printf("empty set");
	else
	{
		sort(interval + 1, interval + 1 + interval_num);
		for(int i = 1; i <= interval_num; i ++)
		{
			Interval &tmp = interval[i];
			if(tmp.st & 1)
				printf("(%d", (tmp.st - 1) / 2);
			else
				printf("[%d", tmp.st / 2);
			printf(",");
			if(tmp.en & 1)
				printf("%d)", (tmp.en + 1) / 2);
			else
				printf("%d]", tmp.en / 2);
			printf(" ");
		}
	}
	printf("\n");
}
Example #12
0
void elimDups(vector<string> &vec) {
  sort(vec.begin(), vec.end());
  auto end_unique = unique(vec.begin(), vec.end());
  vec.erase(end_unique, vec.end());
}
Example #13
0
BigInt stupid(vector<BigInt>& vertexes)
{
  sort(vertexes.begin(), vertexes.end());

  return stupid(vertexes, 0, vertexes.size() -  1);
}
Example #14
0
void RayCaster::castRay(const Vector3& start, const Vector3& dir, int flags, uint32_t maxResults)
{
	if (!handler) {
		throw InvalidStateException("RayCaster::castRay() called without an active RayCastingHandler!",
				__FILE__, __LINE__);
	}

	Vector3 ndir = dir;
	ndir.normalize();

	if (maxResults == 0)
		maxResults = UINT32_MAX;

	uint32_t numResults = 0;

	vector<CastingResult> results;

	handler->startRayCasting(start, ndir, flags);

	void* userPtr;

	RayCastingHandler::ObjectData objData;

	uint32_t objID = 0;

	void* objUserPtr;
	while (handler->nextObject(objData, objUserPtr)) {
		bool objHasResults = false;

		if ((objData.flags & RayCastingHandler::ObjectDataFlagBoundingSphere)  !=  0) {
			if (!IntersectRaySphereSimple(start, ndir, objData.boundingSphereCenter, objData.boundingSphereRadius)) {
				handler->finishObject(objUserPtr);
				objID++;
				continue;
			}
		}
		if ((objData.flags & RayCastingHandler::ObjectDataFlagBoundingBox)  !=  0) {
			float rMin, rMax;
			bool intersects = IntersectRayBox (
					start, ndir,
					objData.boundingBoxMin, objData.boundingBoxExtX, objData.boundingBoxExtY, objData.boundingBoxExtZ,
					rMin, rMax
					);

			if (!intersects) {
				handler->finishObject(objUserPtr);
				objID++;
				continue;
			}
		}

		if (!handler->loadObjectDetails(objUserPtr)) {
			handler->finishObject(objUserPtr);
			objID++;
			continue;
		}

		RayCastingHandler::SphereData sphereData;
		while (numResults < maxResults  &&  handler->nextSphere(objUserPtr, sphereData, userPtr)) {
			if ((flags & CalculateIntersectionPosition)  !=  0  ||  (flags & Sorted)  !=  0) {
				Vector3 pointA, pointB;
				bool intersects = IntersectRaySphere (
						start, ndir,
						objData.modelMatrix * sphereData.center, sphereData.radius,
						pointA, pointB);

				if (intersects) {
					RayCastingHandler::SphereResult sres;
					sres.pointA = pointA;
					sres.pointB = pointB;
					sres.rayRa = (pointA - start).dot(ndir);
					sres.rayRb = (pointB - start).dot(ndir);

					if ((flags & Sorted)  !=  0) {
						CastingResult res;
						res.objID = objID;
						res.rayR = sres.rayRa;
						res.type = Sphere;
						res.objUserPtr = objUserPtr;
						res.userPtr = userPtr;
						res.sphereRes = sres;

						results.push_back(res);
					} else {
						handler->sphereIntersectionReported(sres, objUserPtr, userPtr);
						numResults++;
					}

					objHasResults = true;
				}
			} else {
				if (IntersectRaySphereSimple(start, ndir, objData.modelMatrix * sphereData.center, sphereData.radius)) {
					RayCastingHandler::SphereResult sres;

					handler->sphereIntersectionReported(sres, objUserPtr, userPtr);
					numResults++;

					objHasResults = true;
				}
			}
		}

		RayCastingHandler::BoxData boxData;
		while (numResults < maxResults  &&  handler->nextBox(objUserPtr, boxData, userPtr)) {
			Vector3 boxOrigin = boxData.min;
			Vector3 boxCornerX(boxData.max.getX(), boxOrigin.getY(), boxOrigin.getZ());
			Vector3 boxCornerY(boxOrigin.getX(), boxData.max.getY(), boxOrigin.getZ());
			Vector3 boxCornerZ(boxOrigin.getX(), boxOrigin.getY(), boxData.max.getZ());

			Vector3 wboxOrigin = objData.modelMatrix * boxOrigin;
			Vector3 wboxExtX = (objData.modelMatrix * boxCornerX) - wboxOrigin;
			Vector3 wboxExtY = (objData.modelMatrix * boxCornerY) - wboxOrigin;
			Vector3 wboxExtZ = (objData.modelMatrix * boxCornerZ) - wboxOrigin;

			float rMin, rMax;

			bool intersects = IntersectRayBox (
					start, ndir,
					wboxOrigin, wboxExtX, wboxExtY, wboxExtZ, rMin, rMax
					);

			if (intersects) {
				RayCastingHandler::BoxResult bres;

				bres.intersectionPoints[0] = start + dir*rMin;
				bres.intersectionPoints[1] = start + dir*rMax;

				bres.intersectionRayR[0] = rMin;
				bres.intersectionRayR[1] = rMax;

				if ((flags & Sorted)  !=  0) {
					CastingResult res;
					res.objID = objID;
					res.rayR = rMin;
					res.type = Box;
					res.objUserPtr = objUserPtr;
					res.userPtr = userPtr;
					res.boxRes = bres;

					results.push_back(res);
				} else {
					handler->boxIntersectionReported(bres, objUserPtr, userPtr);
					numResults++;
				}

				objHasResults = true;
			}
		}



		RayCastingHandler::MeshData meshData;
		while (handler->nextMesh(objUserPtr, meshData, userPtr)) {
			for (uint32_t i = 0 ; i < meshData.numFaces ; i++) {
				uint32_t idx0 = meshData.indices[i*3];
				uint32_t idx1 = meshData.indices[i*3 + 1];
				uint32_t idx2 = meshData.indices[i*3 + 2];

				float s, t;
				float rayR;

				Vector3 vtx0(meshData.vertices[idx0*3], meshData.vertices[idx0*3+1], meshData.vertices[idx0*3+2]);
				Vector3 vtx1(meshData.vertices[idx1*3], meshData.vertices[idx1*3+1], meshData.vertices[idx1*3+2]);
				Vector3 vtx2(meshData.vertices[idx2*3], meshData.vertices[idx2*3+1], meshData.vertices[idx2*3+2]);

				bool intersects = IntersectRayTriangle(start, ndir,
						objData.modelMatrix * vtx0,
						objData.modelMatrix * vtx1,
						objData.modelMatrix * vtx2,
						s, t, rayR
						);

				if (intersects) {
					RayCastingHandler::MeshResult mres;
					mres.faceIndex = i;
					mres.s = s;
					mres.t = t;
					mres.rayR = rayR;

					if ((flags & Sorted)  !=  0) {
						CastingResult res;
						res.objID = objID;
						res.rayR = rayR;
						res.type = Mesh;
						res.objUserPtr = objUserPtr;
						res.userPtr = userPtr;
						res.meshRes = mres;

						results.push_back(res);
					} else {
						handler->meshIntersectionReported(mres, objUserPtr, userPtr);
						numResults++;
					}

					objHasResults = true;
				}
			}
		}

		if ((flags & Sorted)  ==  0  ||  !objHasResults) {
			handler->finishObject(objUserPtr);
		}

		objID++;
	}

	if ((flags & Sorted)  !=  0) {
		CastingResultComparator comp;

		if (maxResults >= results.size()) {
			sort(results.begin(), results.end(), comp);
		} else {
			partial_sort(results.begin(), results.begin() + numResults, results.end(), comp);
		}

		set<uint32_t> finishedObjs;

		uint32_t i = 0;
		for (vector<CastingResult>::iterator it = results.begin() ; it != results.end()  &&  i < maxResults ; it++, i++) {
			CastingResult& res = *it;

			if (res.type == Sphere) {
				handler->sphereIntersectionReported(res.sphereRes, res.objUserPtr, res.userPtr);
			} else if (res.type == Box) {
				handler->boxIntersectionReported(res.boxRes, res.objUserPtr, res.userPtr);
			} else {
				handler->meshIntersectionReported(res.meshRes, res.objUserPtr, res.userPtr);
			}
		}

		for (vector<CastingResult>::iterator it = results.begin() ; it != results.end() ; it++) {
			CastingResult& res = *it;

			if (finishedObjs.insert(res.objID).second) {
				handler->finishObject(res.objUserPtr);
			}
		}
	}

	handler->finishRayCasting();
}
Example #15
0
Text parse(bool cli, istream& is) {
	// some initialization
	int line = 0;
	ifstream file;
	std::streambuf *backup = is.rdbuf();

	// if text is not from files
	if (cli) {
		bool invalid = true;
		string dir;
		do {
			line = headline();
			cout << "\n\n\n\n";
			if (dir == "") cout << "\n\n";
			else cout << "        You can't break this, "
				<< "I'm handling errors properly!\n\n";
			cout << "        Please insert the directory "
				<< "of a text file for analysis.\n";
			cout << "        The file should be pre-formatted "
				<< "like this:\n\n";
			cout << "             <Title>\n";
			cout << "             <Author>\n\n";
			cout << "             <text to analyze>\n\n";
			cout << "        or pipe an input stream before "
				<< "executing.\n";
			for (int i = line += 9 + 7; i<25 - 1; i++) cout << "\n";
			cout << "Directory: ";
			if (getline(is, dir)) {
				(file.open(dir.c_str(), ifstream::in));
				if (file) invalid = false;
                else {
                    cout << "file could not be opened\n";
//                    exit(69);
                }
            }
		} while (invalid);
		is.rdbuf(file.rdbuf());
		cout << "istream mapped to cin.\n";
	}

	// check how many paragraphs are there
	string paragraph; int no_of_pars = 0; vector<string> pars;
	while (getline(is, paragraph)) {
		if (paragraph != "") {
			++no_of_pars;
			pars.push_back(paragraph);
		}
	}

	// invalid format
	if (no_of_pars < 2) {
        is.rdbuf(backup);
        file.close();
        
		line = headline();
		cout << "\n\n\n\n\n\n\n                     Invalid format!"
			<< "\n                     Error: "
			<< "file has less than 2 lines."
			<< "\n\n                     Try again maybe?";
		for (int i = line + 11; i < 24; i++) cout << "\n";
		if (!cli) {
			//cout << "piped, quitting";
			exit(1);
		}
		cout << "Press Enter to try again.";
		is.ignore();
		return parse(cli, is);
	}

	// new text object, having all word pairs
	Text text(pars[0], pars[1]);
	text.paragraphs = no_of_pars - 2;

	// count words and split
	vector<string> words;		// word vector
	int no_of_sentences = 0;
	for (auto iter = pars.begin() + 2; iter != pars.end(); ++iter) {
		no_of_sentences += split(*iter, words);
	}
	text.sentences = no_of_sentences;
	text.words = words.size();

	// sorting word
	sort(words.begin(), words.end());

	// reusing variable paragraph for temp read word
	paragraph = "";
	int times_appeared = 0;
	for (auto iter = words.begin(); iter != words.end(); ++iter) {
		if (!iter->compare(paragraph)) {
			++times_appeared;
		}
		else {
			if (times_appeared != 0) text.wordMap.insert(pair<string, int>(paragraph, times_appeared));
			cout << "pushed in " << paragraph << " " << times_appeared << "\n";
			times_appeared = 1;
		}
		paragraph = *iter;
	}
	// the last one never got included, so we have to manually add it
	text.wordMap.insert(pair<string, int>(paragraph, times_appeared));
	cout << "pushed in " << paragraph << " " << times_appeared << "\n";

	cout << "pushed all in, size " << text.wordMap.size() << "\n";

	// return cin rdbuf
	if (cli) {
		is.rdbuf(backup);
		cout << "istream (cin) reverted.\n";
		file.close();
		cout << "Opened file closed.\n";
	}

	cout << "Parse successful.\n";
	return text;
}
Example #16
0
int main(void){
	int t;
	scanf("%d",&t);
	for(;t>0;t--){
		int n,m,q;
		scanf("%d%d%d",&n,&m,&q);
		int i,j;
		vector<int> aa,bb;
		for(i=0;i<=m;i++)
		    aa.push_back(0),bb.push_back(0);
		for(i=0;i<n;i++)
		   scanf("%d",&g[i]),ans[i]=-2,w[i].oc.clear();
		for(i=0;i<m;i++){
		   scanf("%d",&p[i]);
		   p[i]--;
		   w[p[i]].oc.push_back(i);
		}
		for(i=0;i<q;i++){
			int a1,b1,c1;
			scanf("%d%d%d",&a1,&b1,&c1);
			r[i].a=--a1,r[i].b=--b1,r[i].c=c1;
			aa[a1]+=c1;
			aa[b1+1]-=c1; 
		}
		for(i=1;i<m;i++)
		  aa[i]+=aa[i-1];
		vector<int> id1;
		vector<int> id;
		int cnta=0,cntb=0;
		vector<int> x1,x2;
		vector<int> l1,l2;
		for(i=0;i<m;i++)
		  id.push_back(0);
		for(i=0;i<n;i++){
			if(g[i]<=sum(i,aa)){
				for(j=0;j<w[i].oc.size();j++)
				   cnta++,l1.push_back(w[i].oc[j]);
				x1.push_back(i);	
			} 
			else{
				for(j=0;j<w[i].oc.size();j++)
				   cntb++,l2.push_back(w[i].oc[j]);
				x2.push_back(i);
			} 
		} 
		sort(l1.begin(),l1.end());
		sort(l2.begin(),l2.end());
		for(i=0;i<cnta;i++)
		   id[l1[i]]=i;
		for(i=0;i<cntb;i++)
		   id[l2[i]]=i;
		for(i=0;i<q;i++){        //³B²z°Ï¶¡ 
		   vector<int>::iterator e=lower_bound(l1.begin(),l1.end(),r[i].a);
		   if(e!=l1.end()) r[i].a=id[*e];
		   else{
		   	  r[i].a=0;
		   	  r[i].b=0;
		   	  r[i].c=0;
		   	  continue;
		   }
		   e=upper_bound(l1.begin(),l1.end(),r[i].b);
		   if(e!=l1.begin()) e=e-1;
		   if(*e>r[i].b) r[i].c=0;
		   r[i].b=id[*e];
		}
		for(i=0;i<n;i++)
		  for(j=0;j<w[i].oc.size();j++)
		      w[i].oc[j]=id[w[i].oc[j]];
		if(x1.size()>0) cal(bb,x1,0,q,cnta);
		for(i=0;i<n;i++){
		  if(i) printf(" ");
		  printf("%d",ans[i]+1);
		}
		printf("\n");
	}
	return 0;
}
Example #17
0
unique_ptr<DecisionTree> trainTree(ExampleIt first,
                                   ExampleIt last,
                                   size_t maxDepth,
                                   float minGain) {
  if (first >= last) return nullptr;
  if (maxDepth == 0) return nullptr;

  size_t numFeatures = first->features.size();
  size_t p = 0, n = 0;
  for (auto it = first; it != last; ++it) {
    if (it->label) {
      ++p;
    } else {
      ++n;
    }
  }

  float bestGain = -1;
  size_t splitIndex;
  size_t splitFeature;
  float splitValue;

  for (size_t i = 0; i < numFeatures; ++i) {
    // Sort by feature i
    sort(first, last, [=](const Example& a, const Example& b) {
        return a.features[i] < b.features[i];
      });

    size_t p1 = 0, n1 = 0;
    for (ExampleIt it = first; it != last; ++it) {
      if (it != first && it->features[i] != (it - 1)->features[i]) {
        float gain = infoGain(p, n, p1, n1);
        if (gain > bestGain) {
          bestGain = gain;
          splitIndex = it - first;
          splitFeature = i;
          splitValue = it->features[i];
        }
      }
      if (it->label) {
        ++p1;
      } else {
        ++n1;
      }
    }
  }

  unique_ptr<DecisionTree> tree(new DecisionTree);
  tree->value = (float) p / (p + n);
  
  if (bestGain > minGain) {
    tree->splitFeature = splitFeature;
    tree->splitValue = splitValue;
    
    sort(first, last, [=](const Example& a, const Example& b) {
        return a.features[splitFeature] < b.features[splitFeature];
      });

    tree->left = std::move(trainTree(first,
                                     first + splitIndex,
                                     maxDepth - 1,
                                     minGain));
    tree->right = std::move(trainTree(first + splitIndex,
                                      last,
                                      maxDepth - 1,
                                      minGain));
  }

  return tree;
}
Example #18
0
void cal(vector<int> base,vector<int> v,int st,int ed,int cnt){
	int i,j;
//	printf("%d %d:\n",st,ed);
	if(st+1==ed){
		for(i=0;i<v.size();i++)
		    ans[v[i]]=st;
		return ;
	} 
	vector<int> base2,base3;
	vector<int> fff;
	for(i=0;i<=cnt;i++)
	  fff.push_back(0);
	int mid=(st+ed)/2;
	for(i=st;i<mid;i++){
	//	printf("%d: %d %d %d\n",i,r[i].a,r[i].b,r[i].c);
		fff[r[i].a]+=r[i].c;
		fff[r[i].b+1]-=r[i].c;
	}  
	for(i=1;i<cnt;i++)
	   fff[i]+=fff[i-1];
	for(i=0;i<cnt;i++)
	   base[i]+=fff[i]; 
	int cnta=0,cntb=0;
	vector<int> x1,x2;
	vector<int> l1,l2;
	vector<int> id2;
	for(i=0;i<cnt;i++)
	  id2.push_back(0);
	for(i=0;i<v.size();i++){
		int d=v[i];
	//	printf("@%d %d %d %d\n",st,ed,d,sum(d,base));
		if(g[d]<=sum(d,base)){
			for(j=0;j<w[d].oc.size();j++)
			   cnta++,l1.push_back(w[d].oc[j]);
			x1.push_back(d);	
		} 
		else{
			for(j=0;j<w[d].oc.size();j++)
			   cntb++,l2.push_back(w[d].oc[j]);
			x2.push_back(d);
		} 
	} 
	sort(l1.begin(),l1.end());
	sort(l2.begin(),l2.end());
	for(i=0;i<l2.size();i++)
	  base3.push_back(base[l2[i]]);
	for(i=0;i<cnt;i++)
	  base[i]-=fff[i];
	for(i=0;i<l1.size();i++)
	  base2.push_back(base[l1[i]]);  
	for(i=0;i<cnta;i++)
	   id2[l1[i]]=i;
	for(i=0;i<cntb;i++)
	   id2[l2[i]]=i;
	vector<int>::iterator e;
	for(i=st;i<mid;i++){
	       e=lower_bound(l1.begin(),l1.end(),r[i].a);
		   if(e!=l1.end()) r[i].a=id2[*e];
		   else{
		   	  r[i].a=0;
		   	  r[i].b=0;
		   	  r[i].c=0;
		   	  continue;
		   }
		   e=upper_bound(l1.begin(),l1.end(),r[i].b);
		   if(e!=l1.begin()) e=e-1; 
		   if(*e>r[i].b) r[i].c=0;
		   r[i].b=id2[*e];
	}
	for(i=mid;i<ed;i++){
		   e=lower_bound(l2.begin(),l2.end(),r[i].a);
		   if(e!=l2.end()) r[i].a=id2[*e];
		   else{
		   	  r[i].a=0;
		   	  r[i].b=0;
		   	  r[i].c=0;
		   	  continue;
		   }
		   e=upper_bound(l2.begin(),l2.end(),r[i].b);
		   if(e!=l2.begin()) e=e-1; 
		   if(*e>r[i].b) r[i].c=0;
		   r[i].b=id2[*e];
	}
	for(i=0;i<v.size();i++)
		  for(j=0;j<w[v[i]].oc.size();j++)
		      w[v[i]].oc[j]=id2[w[v[i]].oc[j]];
	if(x1.size()>0) cal(base2,x1,st,mid,cnta);
	if(x2.size()>0) cal(base3,x2,mid,ed,cntb);
}
Example #19
0
/////////////////////////////////////////////////////////////////////
// Advection integration
// Returns the next direction for RTT
////////////////////////////////////////////////////////////////////
Vector RTTFibers::advecIntegrate( Vector vin, const FMatrix &tensor, Vector e1, Vector e2, Vector e3, float t_number ) 
{
    Vector vout, vprop, ee1, ee2, ee3;
    float dp1, dp2, dp3;
    float cl = m_pTensorsInfo->getTensorsFA()->at(t_number);
    float puncture = getPuncture();

    GLfloat flippedAxes[3];
    m_pTensorsInfo->isAxisFlipped(X_AXIS) ? flippedAxes[0] = -1.0f : flippedAxes[0] = 1.0f;
    m_pTensorsInfo->isAxisFlipped(Y_AXIS) ? flippedAxes[1] = -1.0f : flippedAxes[1] = 1.0f;
    m_pTensorsInfo->isAxisFlipped(Z_AXIS) ? flippedAxes[2] = -1.0f : flippedAxes[2] = 1.0f;

    // Unit vectors of local basis (e1 > e2 > e3)
    ee1.x = flippedAxes[0] * (tensor(0,0) * e1.x + 
            tensor(0,1) * e1.y + 
            tensor(0,2) * e1.z);

    ee1.y = flippedAxes[1] * (tensor(1,0) * e1.x + 
            tensor(1,1) * e1.y + 
            tensor(1,2) * e1.z);

    ee1.z = flippedAxes[2] * (tensor(2,0) * e1.x +
            tensor(2,1) * e1.y + 
            tensor(2,2) * e1.z);
    //e2
    ee2.x = flippedAxes[0] * (tensor(0,0) * e2.x + 
            tensor(0,1) * e2.y + 
            tensor(0,2) * e2.z);

    ee2.y = flippedAxes[1] * (tensor(1,0) * e2.x + 
            tensor(1,1) * e2.y + 
            tensor(1,2) * e2.z);

    ee2.z = flippedAxes[2] * (tensor(2,0) * e2.x +
            tensor(2,1) * e2.y + 
            tensor(2,2) * e2.z);
    //e3
    ee3.x = flippedAxes[0] * (tensor(0,0) * e3.x + 
            tensor(0,1) * e3.y + 
            tensor(0,2) * e3.z);

    ee3.y = flippedAxes[1] * (tensor(1,0) * e3.x + 
            tensor(1,1) * e3.y + 
            tensor(1,2) * e3.z);

    ee3.z = flippedAxes[2] * (tensor(2,0) * e3.x +
            tensor(2,1) * e3.y + 
            tensor(2,2) * e3.z);

    if( vin.Dot(ee1) < 0.0 )
    {
      ee1 *= -1;
    }
    
    ee1.normalize();
    ee2.normalize();
    ee3.normalize();

    // Lets first expand vin in local basis
    dp1 = vin.Dot(ee1);
    dp2 = vin.Dot(ee2);
    dp3 = vin.Dot(ee3);

    //Sort eigen values
    float eValues[] = { m_pTensorsInfo->getTensorsEV()->at(t_number)[0], m_pTensorsInfo->getTensorsEV()->at(t_number)[1], m_pTensorsInfo->getTensorsEV()->at(t_number)[2] };
    sort( eValues, eValues+3 );

    // Compute vout
    vout = dp1 * eValues[0] * ee1 + dp2 * eValues[1] * ee2 + dp3 * eValues[2] * ee3;

    // Normalization (see Lazar paper for more explanations)
    vout.normalize();
    ee1.normalize();
    vin.normalize();

    vprop = cl * ee1 + (1.0 - cl) * ( (1.0 - puncture) * vin + puncture * vout );
    return vprop;
}
Example #20
0
void Bmp::fillPolygon(
   const    vector<int> &points,
   unsigned char        red,
   unsigned char        green,
   unsigned char        blue
)
{
   int xMin = 0;
   int yMin = 0;
   int xMax = 0;
   int yMax = 0;

   for(int i = 0, n = points.size(); i < n; i += 2)
   {
      int x = points[i];
      int y = points[i + 1];
      
      if(i == 0)
      {
         xMin = xMax = x;
         yMin = yMax = y;
      }
      else
      {
         if(x < xMin)      xMin = x;
         else if(x > xMax) xMax = x;

         if(y < yMin)      yMin = y;
         else if(y > yMax) yMax = y;
      }
   }

   typedef vector<int>     YValues;
   typedef vector<YValues> Buffer;

   int width = (xMax - xMin) + 1;

   Buffer theBuffer;

   for(int i = 0; i < width; i ++)
      theBuffer.push_back(YValues());

   for(int i = 2, n = points.size(); i < n; i += 2)
   {
      int x0 = points[i - 2];
      int y0 = points[i - 1];

      int x1 = points[i];
      int y1 = points[i + 1];

      if(x0 == x1)
      {
         theBuffer[x0 - xMin].push_back(y0);
         theBuffer[x0 - xMin].push_back(y1);
      }
      else 
      {
         double delta = (y1 - y0) / (double)(x1 - x0);
         int    start = 0;
         int    stop  = 0;
         double y     = 0.0;
         
         if(x0 < x1)
         {
            y     = y0;
            start = x0;
            stop  = x1;
         }
         else
         {
            y     = y1;
            start = x1;
            stop  = x0;
         }

         for(int j = start; j < stop; j ++)
         {
            int yValue = (int)(y + 0.5);

            theBuffer[j - xMin].push_back(yValue);

            y += delta;
         }
      }
   }

   for(int i = 0, n = theBuffer.size(); i < n; i ++)
      sort(theBuffer[i].begin(), theBuffer[i].end());

   for(int i = 0, n = theBuffer.size(); i < n; i ++)
   {
      for(int j = 1, nn = theBuffer[i].size(); j < nn; j += 2)
      {
         drawLine(
            xMin + i,
            theBuffer[i][j],
            xMin + i,
            theBuffer[i][j - 1],
            red, green, blue
         );
      }
   }
}
/** Calcolo della partizione prodotto (simmetrico).
 * Il risultato è un oggetto partizione completo, con tutte le proprieta' definite.
 * Per il calcolo di una distanza è eccessivo - meglio usare la classe distance,
 *  che implementa lo stesso codice troncato e senza temporanei inutili.
 *
 * @param p1 Primo fattore
 * @param p2 Secondo fattore
 * @return L'oggetto partizione prodotto
 */
void general_partition::product(const general_partition & p1, const general_partition & p2) {
    label_t mu;
    label_t begin;
    allocate(p1.N);
    atomi.resize(N);

    /** I label del prodotto sono rappresentati dalle coppie (pair<label_t, label_t>)
     * di label dei fattori. Il vettore @c label_index contiene la coppia <label_prodotto, indice>.\n
     * Per riconoscere gli atomi, ordino il vettore label_index:
     *  il risultato sarà un vettore ordinato, per cui riconosciamo gli atomi come elementi
     *  contigui con lo stesso label. Il label è temporaneo, gli atomi avranno indice
     *  progressivo.
     * Esempio:
     * (0,1) - 1
     * (0,2) - 2
     * (1,0) - 3
     * (1,0) - 3
     * (1,2) - 4
     */

    /** Il vettore @e label_index contiene i seguenti membri:
     *  - label_index[i].first - indice (temp) del prodotto.
     *  - label_index[i].second - indica la posizione del sito nella partizione,
     *     è utilizzato per indicizzare i cambiamenti e gli accessi ai vettori labels[], ecc.
     */
    vector<pair<uint32_t, label_t> > label_index(N);
    n = 0;
    entropia_shannon = 0;

    label_t count = 0;
    label_t old_count = 0;
    int fiddle = 0;
    /** Gli elementi sono ordinati atomo-per-atomo. Per ogni sito dell'atomo1, si controllano
     * tutti i label di appartenenza per la partizione2 - i diversi atomi incontrati
     * formano un diverso atomo della partizione prodotto!
     * Si utilizza sempre il sort, ma stavolta per ogni atomo della partizione 1,
     * riducendo trasticamente i tempi, poiché sono state struttate le informazioni sulla
     * disposizione dei vari elementi.
     */
    for (label_t atom_index = 0; atom_index < p1.n; atom_index++) {
        /* fiddle factor serve per distinguere atomi con il primo indice diverso:
         * infatti salviamo solo le etichette dell'atomo2, quindi se queste sono identiche,
         * ma differiscono per l'atomo1, vanno distinte!
         * Si vuole evitare il seguente caso:
         * (0,1)
         * (1,1)
         * che sarebbero riconosciuti come uguali. Per cui si setta il primo bit del label,
         * alternativamente 0 e 1, per distinguere i vari atomi.
         */
        fiddle = (fiddle) ? 0 : (1<<(sizeof(label_t)*8-1));
        for (Iter_t ii = p1.begin(atom_index); ii != p1.end(); ii++)
            label_index[count++] = make_pair(fiddle | p2.labels[*ii], *ii);

        sort(&label_index[old_count], &label_index[count]);
        old_count = count;
    }
    /* Dopo il sort, riconosciamo gli atomi. Il primo sito sicuramente inizia un nuovo
     * atomo, per i successivi riconosciamo un atomo non appena il label cambia
     */
    begin = 0;
    uint32_t old_val = label_index[0].first;
    
    //we skip over the first value, so initialize here
    labels[label_index[0].second] = n;
    prev_site[label_index[0].second] = label_index[0].second;

    for (label_t i = 1; i < N; i++) {
        label_t & LAST_POS = label_index[i - 1].second;
        label_t & THIS_POS = label_index[i].second;
        //whenever we find a new atom
        if (label_index[i].first != old_val) {
            //a new atom starts

            //the closed (old)atom's length is calculated
            mu = i - begin;
            atomi[n].start = label_index[begin].second;
            atomi[n].size = mu;
            atomi[n].end = LAST_POS;
            //the new one is ready to go
            //prev_site del sito corrente è il sito stesso
            prev_site[THIS_POS] = THIS_POS;
            n++;
            begin = i;
            //cache the new label to check
            old_val = label_index[i].first;

            //we add the entropy, with the trick mu>0 and when mu=1 the log is 0
            if (mu > 1)
                entropia_shannon += (double) mu * mylog[mu];
        } else {
            //prev site del sito corrente è il precedente trovato nello stesso atomo
            prev_site[THIS_POS] = LAST_POS;
            //il sito attuale è sicuramente l'ultima posizione trovata per l'atomo corrente
            atomi[n].end = THIS_POS;
        }
        //relabel anyway con l'indice di atomo corrente
        labels[THIS_POS] = n;
    }
    //the last one, so it's not left hanging
    mu = N - begin;
    atomi[n].start = label_index[begin].second;
    atomi[n].size = mu;
    atomi[n].end = label_index[N - 1].second;
    entropia_shannon += mu * mylog[mu];
    //il numero di atomi trovati è l'indice corrente +1
    n++;

    //normalize the entropy
    entropia_shannon = -entropia_shannon / N + mylog[N];
    entropia_topologica = mylog[n];
}
Example #22
0
void sort_word(string &word) 
{
    //sorts the word
    sort(word.begin(), word.end());   
}
Example #23
0
void CLIPlayer::sortHand()
{
    Card::cardsuit trump = agent_->getTrumpCard().getSuit();
    sort(hand_.begin(), hand_.end(), CardComp(trump));
}
void FeatureCalculate::rpca(CloudPtr cloud,NormalPtr normals, int num_of_neighbors, float Pr, float epi,float reliability)
{
    pcl::KdTreeFLANN<CloudItem> kdtree;
    kdtree.setInputCloud(cloud);
    normals->resize(cloud->size());
    #pragma omp parallel for
    for (int j = 0; j < cloud->size(); j++) {
        CloudPtr cloud_h(new Cloud);
        CloudPtr cloud_final(new Cloud);
        vector<int> point_id_search;
        vector<float> point_distance;
        int point_num = kdtree.nearestKSearch(j,num_of_neighbors,point_id_search,point_distance);
        point_distance.clear();
        vector<PlanePoint> plane_points;
        plane_points.resize(point_num);
        if (point_num > 3) {
            int iteration_number;
            int h_free;
            h_free = int(reliability * point_num);
            iteration_number = compute_iteration_number(Pr, epi, h_free);
            vector<PlanSegment> planes;
            for (int i = 0; i < iteration_number; i++) {
                CloudPtr points(new Cloud);
                int num[3];
                for (int n = 0; n < 3; n++) {
                    num[n] = rand() % point_num;
                    points->push_back(cloud->points[point_id_search[num[n]]]);
                }
                if (num[0] == num[1] || num[0] == num[2] || num[1] == num[2])
                    continue;
                PlanSegment a_plane;
                pca(points,a_plane);
                for (int n = 0; n < point_num; n++) {
                    plane_points[n].dis =compute_distance_from_point_to_plane(cloud->points[point_id_search[n]],a_plane);
                    plane_points[n].point=cloud->points[point_id_search[n]];
                }
                std::sort(plane_points.begin(), plane_points.end(), CmpDis);
                for (int n = 0; n < h_free; n++) {
                    CloudItem temp_point=plane_points[n].point;
                    cloud_h->points.push_back(temp_point);
                }
                pca(cloud_h,a_plane);
                cloud_h->points.clear();
                planes.push_back(a_plane);
            }
            sort(planes.begin(), planes.end(), Cmpmin_value);
            PlanSegment final_plane;
            final_plane = planes[0];
            planes.clear();
            vector<float> distance;
            vector<float> distance_sort;
            for (int n = 0; n < point_num; n++) {
                float dis_from_point_plane;
                dis_from_point_plane =compute_distance_from_point_to_plane(cloud->points[point_id_search[n]],final_plane);
                distance.push_back(dis_from_point_plane);
                distance_sort.push_back(dis_from_point_plane);
            }
            sort(distance_sort.begin(), distance_sort.end());
            float distance_median;
            distance_median = distance_sort[point_num / 2];
            distance_sort.clear();
            float MAD;
            vector<float> temp_MAD;
            for (int n = 0; n < point_num; n++) {
                temp_MAD.push_back(abs(distance[n] - distance_median));
            }
            sort(temp_MAD.begin(), temp_MAD.end());
            MAD = 1.4826 * temp_MAD[point_num / 2];
            if (MAD == 0) {
                for (int n = 0; n < point_num; n++) {
                    CloudItem temp_point=cloud->points[point_id_search[n]];
                    cloud_final->points.push_back(temp_point);
                }
            } else {
                for (int n = 0; n < point_num; n++) {
                    float Rz;
                    Rz = (abs(distance[n] - distance_median)) / MAD;
                    if (Rz < 2.5) {
                        CloudItem temp_point=cloud->points[point_id_search[n]];
                        cloud_final->points.push_back(temp_point);
                    }
                }
            }
            point_id_search.clear();
            if (cloud_final->points.size() > 3)
            {
                pca(cloud_final,final_plane);
                normals->points[j]= final_plane.normal;
            } else {
                normals->points[j].normal_x = 0.0;
                normals->points[j].normal_y = 0.0;
                normals->points[j].normal_z = 0.0;
                normals->points[j].curvature = 1.0;
            }
            cloud_final->clear();
        } else {
            normals->points[j].normal_x = 0.0;
            normals->points[j].normal_y = 0.0;
            normals->points[j].normal_z = 0.0;
            normals->points[j].curvature = 1.0;
        }    
    }
}
void GeneticAlgorithm<PopulationPropertiesType>::sortByFitness() {
    sort((*populationP).begin(), (*populationP).end(), [](GaStruct x, GaStruct y){ return x.fitness < y.fitness; });
}
Example #26
0
void CaicWriter::writeData
(ContTraitMatrix& iContWrangler, DiscTraitMatrix& iDiscWrangler)
{
	// Preconditions:

	// Main:
	// gather & sort species names
	stringvec_t theSppNames;
	ContTraitMatrix::size_type theNumContRows = iContWrangler.countRows ();
	DiscTraitMatrix::size_type theNumDiscRows = iDiscWrangler.countRows ();
	if (theNumContRows < theNumDiscRows)
	{
		for (DiscTraitMatrix::size_type i = 0; i < theNumDiscRows; i++)
		{
			theSppNames.push_back (iDiscWrangler.getRowName (i));
		}
	}
	else
	{
		for (ContTraitMatrix::size_type i = 0; i < theNumContRows; i++)
		{
			theSppNames.push_back (iContWrangler.getRowName (i));
		}
	}
	sort (theSppNames.begin(), theSppNames.end());

	// print out data
	ContTraitMatrix::size_type theNumContCols = iContWrangler.countCols ();
	DiscTraitMatrix::size_type theNumDiscCols = iDiscWrangler.countCols ();

	// print out col titles
	(*mDataStreamP) << "Spp names";
	for (ContTraitMatrix::size_type i = 0; i < theNumContCols; i++)
		(*mDataStreamP) << "\t" << iContWrangler.getColName (i);
	for (DiscTraitMatrix::size_type i = 0; i < theNumDiscCols; i++)
		(*mDataStreamP) << "\t" << iDiscWrangler.getColName (i);
	(*mDataStreamP)  << endl;

	// print out data
	stringvec_t::iterator p;
	for (p = theSppNames.begin(); p != theSppNames.end(); p++)
	{
		// print out spp name
		(*mDataStreamP) << *p;

		// print out cont data
		for (ContTraitMatrix::size_type i = 0; i < theNumContCols; i++)
		{
			/*
			std::string theContStr = iContWrangler.getData (p->c_str(), i);
			if (theContStr == "?")
				theContStr = "-9";
			(*mDataStreamP) << "\t" << theContStr;
			*/
			(*mDataStreamP) << "\t" << iContWrangler.getData (p->c_str(), i);;
		}
		// print out disc data
		for (DiscTraitMatrix::size_type i = 0; i < theNumDiscCols; i++)
		{
			// TO DO: need to translate disc data. Big prob
			// see if all numerical?
			std::string theDiscStr = iDiscWrangler.getData (p->c_str(), i);
			// if (theDiscStr == "?")
			// 	theDiscStr = "-9";
			(*mDataStreamP) << "\t" << theDiscStr;
		}

		(*mDataStreamP) << endl;
	}

}
Example #27
0
void elimDups(vector<string> &words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
}
int main()
{
  // create an elevator (capacity 12, speed 5 in/sec)
  const Floor startingFloor(0); // ground floor
  Elevator e(12, 5, startingFloor);
  cout << "The only elevator in this test: " << e << endl;

  // testing the getCapacity function
  cout << "Capacity is " << e.getCapacity();
  if (e.getCapacity() == 12) cout << "(correct)\n"; else cout << "(INCORRECT)\n";

  // move the elevator up for 20 seconds
  e.closeDoor();
  e.setDestination(0);
  e.setDirectionUp();
  int i, count = 0;
  for (i = 0; i < 20; i++)
    e.moveUp();
  e.setIdle();
  e.openDoor();
  cout << "Moved up for 20 seconds: " << e << endl;

  // add riders to the elevator, to capacity
  vector<Rider> riders;
  int n = e.getAvailableSpace();
  for (i = 0; i < n; i++)
    riders.push_back(Rider(startingFloor));
  e.addRiders(riders);
  cout << "Added riders to capacity: " << e << endl;
  cout << "#of riders is " << e.getRiderCount();
  if (e.getRiderCount() == 12) cout << "(correct)\n"; else cout << "(INCORRECT)\n";
  vector<Rider> originalRiders(riders);

  // move down to first floor until it reaches
  e.setDestinationBasedOnRiders();
  e.closeDoor();
  e.setDirectionDown();
  cout << e << endl;

  while(!e.isNearDestination())
  {
    if (e.isDirectionUp()) e.moveUp();
    else if (e.isDirectionDown()) e.moveDown();
    cout << e << endl;
    if (!(++count % 20)) {cout << "Press ENTER to continue...\n"; cin.get();}
  }
  e.moveToDestinationFloor();
  cout << "Moved to destination floor: " << e << endl;

  // done
  e.openDoor();
  riders = e.removeRidersForDestinationFloor();
  cout << "Opened door, let out " << riders.size() << " riders: " << e << endl;
  cout << "#of riders is " << e.getRiderCount();
  if (e.getRiderCount() == 0) cout << "(correct)\n"; else cout << "(INCORRECT)\n";
  e.setIdle();

  // see if same riders got off who got on originally
  if (riders.size() < originalRiders.size())
    cout << "ERROR: LOST RIDERS!\n";
  else if (riders.size() > originalRiders.size())
    cout << "ERROR: MYSTERIOUSLY-CREATED RIDERS!\n";
  else
  {
    sort(riders.begin(), riders.end());
    sort(originalRiders.begin(), originalRiders.end());
    n = riders.size();
    for (i = 0; i < n; i++)
    {
      if (!(riders[i] == originalRiders[i]))
        cout << "ERROR: RIDER#" << i << " HAS NEW IDENTITY!\n";
  } }

  // now, move the elevator down for 20 seconds
  e.closeDoor();
  e.setDestination(0);
  e.setDirectionDown();
  for (i = 0; i < 20; i++)
    e.moveDown();
  e.setIdle();
  e.openDoor();
  cout << "Moved down for 20 seconds: " << e << endl;

  // add a rider going up
  riders.clear();
  riders.push_back(Rider(startingFloor));
  e.addRiders(riders);
  cout << "#of riders is " << e.getRiderCount();
  if (e.getRiderCount() == 1) cout << "(correct)\n"; else cout << "(INCORRECT)\n";

  // move up to first floor until it reaches
  e.setDestinationBasedOnRiders();
  e.closeDoor();
  e.setDirectionUp();
  cout << e << endl;
  while(!e.isNearDestination())
  {
    if (e.isDirectionUp()) e.moveUp();
    else if (e.isDirectionDown()) e.moveDown();
    cout << e << endl;
    if (!(++count % 20)) {cout << "Press ENTER to continue...\n"; cin.get();}
  }
  e.moveToDestinationFloor();
  cout << "Move to starting floor: " << e << endl;

  // done
  e.openDoor();
  e.removeRidersForDestinationFloor();
  e.setIdle();
  cout << "Test end: " << e << endl;
  cout << "#of riders is " << e.getRiderCount();
  if (e.getRiderCount() == 0) cout << "(correct)\n"; else cout << "(INCORRECT)\n";

  // additional testing of your own, if you have any
}
Example #29
0
void AlphaBlendSorter::sortVertices(std::vector<VertexTypes::VertexBasic>& vertices, const DirectX::XMMATRIX &World,
	const DirectX::XMMATRIX &View, const DirectX::XMMATRIX &Projection){

	DirectX::XMFLOAT4X4 floatWorld;
	DirectX::XMStoreFloat4x4(&floatWorld, World);
	DirectX::XMFLOAT4X4 floatView;
	DirectX::XMStoreFloat4x4(&floatView, View);
	DirectX::XMFLOAT4X4 floatProjection;
	DirectX::XMStoreFloat4x4(&floatProjection, Projection);

	std::ofstream fout("Matrix.txt");
	fout << "World:\n\n";
	for (int i = 0; i < 4; i++){
		for (int j = 0; j < 4; j++){
			fout << floatWorld(i, j) << " ";
		}
		fout << '\n';
	}

	fout << "\n\nView:\n\n";
	for (int i = 0; i < 4; i++){
		for (int j = 0; j < 4; j++){
			fout << floatView(i, j) << " ";
		}
		fout << '\n';
	}

	fout << "\n\nProjection:\n\n";
	for (int i = 0; i < 4; i++){
		for (int j = 0; j < 4; j++){
			fout << floatProjection(i, j) << " ";
		}
		fout << '\n';
	}

	DirectX::XMMATRIX worldViewProjection = World * View * Projection;
	//DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixMultiply(World, View);
	//worldViewProjection = DirectX::XMMatrixMultiply(worldViewProjection, Projection);
	//worldViewProjection = DirectX::XMMatrixTranspose(worldViewProjection);

	DirectX::XMFLOAT4X4 worldViewProjectionFloat;
	DirectX::XMStoreFloat4x4(&worldViewProjectionFloat, worldViewProjection);


	fout << "\n\nWorldViewProjection:\n\n";
	for (int i = 0; i < 4; i++){
		for (int j = 0; j < 4; j++){
			fout << worldViewProjectionFloat(i, j) << " ";
		}
		fout << '\n';
	}



	for (int i = 0; i < vertices.size(); i++){
		DirectX::XMVECTOR verticeVector = DirectX::XMLoadFloat4(&vertices[i].Pos);
		verticeVector = DirectX::XMVector4Transform(verticeVector, worldViewProjection);
		DirectX::XMStoreFloat4(&vertices[i].Pos, verticeVector);
	}

	std::vector<VertexTypes::VertexBasicFace> vertexFaces;
	for (int i = 0; i < vertices.size(); i++){
		VertexTypes::VertexBasicFace vbf;
		vbf.faceVertices[0] = vertices[i++];
		vbf.faceVertices[1] = vertices[i++];
		vbf.faceVertices[2] = vertices[i];
		vertexFaces.push_back(vbf);
	}

	sort(vertexFaces.begin(), vertexFaces.end(), VectorCompareFunctions::VertexBasicDistance);
	vertices.resize(0);

	for (int i = 0; i < vertexFaces.size(); i++){
		VertexTypes::VertexBasicFace vbf;
		vbf = vertexFaces[i];
		vertices.push_back(vbf.faceVertices[0]);
		vertices.push_back(vbf.faceVertices[1]);
		vertices.push_back(vbf.faceVertices[2]);
	}

	fout << "\n\nBegin output\n";
	for (std::vector<VertexTypes::VertexBasic>::iterator iter = vertices.begin(); iter < vertices.end(); iter++){

		float Dist = 0.0f;
		Dist += iter->Pos.z;
		iter++;
		Dist += iter->Pos.z;
		iter++;
		Dist += iter->Pos.z;

		fout << "Distance: " << Dist << '\n';
		//fout << "Pos: " << iter->Pos.x << " " << iter->Pos.y << " " << iter->Pos.z << " " << iter->Pos.w << '\n';
		//fout << "Tex: " << iter->Tex.x << " " << iter->Tex.y << '\n';
		//fout << "Norm: " << iter->Normal.x << " " << iter->Normal.y << " " << iter->Normal.z << '\n';
	}

	fout.flush();




}
vector<vector<Ref<FinderPattern> > > MultiFinderPatternFinder::selectBestPatterns(){
  vector<Ref<FinderPattern> > possibleCenters = possibleCenters_;
  
  int size = possibleCenters.size();

  if (size < 3) {
    // Couldn't find enough finder patterns
    throw ReaderException("No code detected");
  }
  
  vector<vector<Ref<FinderPattern> > > results;

  /*
   * Begin HE modifications to safely detect multiple codes of equal size
   */
  if (size == 3) {
    results.push_back(possibleCenters_);
    return results;
  }

  // Sort by estimated module size to speed up the upcoming checks
  //TODO do a sort based on module size
  sort(possibleCenters.begin(), possibleCenters.end(), compareModuleSize);

  /*
   * Now lets start: build a list of tuples of three finder locations that
   *  - feature similar module sizes
   *  - are placed in a distance so the estimated module count is within the QR specification
   *  - have similar distance between upper left/right and left top/bottom finder patterns
   *  - form a triangle with 90° angle (checked by comparing top right/bottom left distance
   *    with pythagoras)
   *
   * Note: we allow each point to be used for more than one code region: this might seem
   * counterintuitive at first, but the performance penalty is not that big. At this point,
   * we cannot make a good quality decision whether the three finders actually represent
   * a QR code, or are just by chance layouted so it looks like there might be a QR code there.
   * So, if the layout seems right, lets have the decoder try to decode.
   */

  for (int i1 = 0; i1 < (size - 2); i1++) {
    Ref<FinderPattern> p1 = possibleCenters[i1];
    for (int i2 = i1 + 1; i2 < (size - 1); i2++) {
      Ref<FinderPattern> p2 = possibleCenters[i2];
      // Compare the expected module sizes; if they are really off, skip
      float vModSize12 = (p1->getEstimatedModuleSize() - p2->getEstimatedModuleSize()) / min(p1->getEstimatedModuleSize(), p2->getEstimatedModuleSize());
      float vModSize12A = abs(p1->getEstimatedModuleSize() - p2->getEstimatedModuleSize());
      if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) {
        // break, since elements are ordered by the module size deviation there cannot be
        // any more interesting elements for the given p1.
        break;
      }
      for (int i3 = i2 + 1; i3 < size; i3++) {
        Ref<FinderPattern> p3 = possibleCenters[i3];
        // Compare the expected module sizes; if they are really off, skip
        float vModSize23 = (p2->getEstimatedModuleSize() - p3->getEstimatedModuleSize()) / min(p2->getEstimatedModuleSize(), p3->getEstimatedModuleSize());
        float vModSize23A = abs(p2->getEstimatedModuleSize() - p3->getEstimatedModuleSize());
        if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) {
          // break, since elements are ordered by the module size deviation there cannot be
          // any more interesting elements for the given p1.
          break;
        }
        vector<Ref<FinderPattern> > test;
        test.push_back(p1);
        test.push_back(p2);
        test.push_back(p3);
        test = FinderPatternFinder::orderBestPatterns(test);
        // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal
        Ref<FinderPatternInfo> info = Ref<FinderPatternInfo>(new FinderPatternInfo(test));
        float dA = FinderPatternFinder::distance(info->getTopLeft(), info->getBottomLeft());
        float dC = FinderPatternFinder::distance(info->getTopRight(), info->getBottomLeft());
        float dB = FinderPatternFinder::distance(info->getTopLeft(), info->getTopRight());
        // Check the sizes
        float estimatedModuleCount = (dA + dB) / (p1->getEstimatedModuleSize() * 2.0f);
        if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) {
          continue;
        }
        // Calculate the difference of the edge lengths in percent
        float vABBC = abs((dA - dB) / min(dA, dB));
        if (vABBC >= 0.1f) {
          continue;
        }
        // Calculate the diagonal length by assuming a 90° angle at topleft
        float dCpy = (float) sqrt(dA * dA + dB * dB);
        // Compare to the real distance in %
        float vPyC = abs((dC - dCpy) / min(dC, dCpy));
        if (vPyC >= 0.1f) {
          continue;
        }
        // All tests passed!
        results.push_back(test);
      } // end iterate p3
    } // end iterate p2
  } // end iterate p1
  if (results.empty()){
    // Nothing found!
    throw ReaderException("No code detected");    
  }
  return results;
}