Can You Guess What This Is Used For

Started by
6 comments, last by RLS0812 10 years, 1 month ago

Sometimes my test code can look very weird when I am attempting to figure something out.

Can you guess what this code block is used to test for ?


                 int num1 = 50;
		 int num2 = 75;
		 int num3 = 100;
		 int num4 = 125;
		 
		 int catche = 0;
		 List<Integer> dump = new ArrayList<Integer>();
		 List<Integer> low = new ArrayList<Integer>();
		 List<Integer> high = new ArrayList<Integer>();
		 
		 dump.add(num1);
		 low.add(catche + 1);
		 catche += num1;
		 high.add(catche);

		 dump.add(num2);
		 low.add(catche + 1);
		 catche += num2;
		 high.add(catche);

		 dump.add(num3);
		 low.add(catche + 1);
		 catche += num3;
		 high.add(catche);

		 dump.add(num4);
		 low.add(catche + 1);
		 catche += num4;
		 high.add(catche);
		 
		 int one = 0;
		 int two = 0;
		 int three = 0;
		 int four = 0;
		 
		 int cnt = 0;
		 while ( cnt != 1001){
		 int temp_rand = rand.nextInt(catche);
		 
		 for (int i = 0; i < dump.size(); i ++ ){
			 if (temp_rand >= low.get(i) && temp_rand <= high.get(i) ){
				 switch (i){
				 case 0: one ++; break;
				 case 1: two ++; break;
				 case 2: three ++; break;
				 case 3: four ++; break;
				 default:break;
				 }
                            //say("\n" + dump.get(i));
			 }
		 }
		 cnt ++;
		 }
		 say("One: " + (int)(((double)one / cnt)* 100)  + "% Two: " + (int)(((double)two / cnt)* 100)  + "% Three: " + 
		 (int)(((double)three / cnt)* 100)  + "% Four: " + (int)(((double)four / cnt)* 100) + "%" );

public void say(String x){
		System.out.println(x);
	}

The answer is: determining probability by weight

Explained -

One object must be picked out of a list of objects, but each object has a different "weight" ( likelihood ) of being picked.

Real Life Example -

You have 5 red marbles.

Your friend has 10 green marbles.

Your second friend has 15 yellow marbles.

Your third friend has 20 blue marbles.

If you put them all in a bag, and pulled out just one, which color would likely be picked?

What is the chance for each color ?

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement
Ahh, running a simulation of the bags of marbles rather than trusting the math. Almost like Mythbusters or something.

int num1 = 50;
int num2 = 75;
int num3 = 100;
int num4 = 125;

524b90d31605fb5d6400004e.gif?w=320

If anyone cares, here is what that code morphed into

.


public class ProbSelect {
	Random rand;

	public ProbSelect(){
		rand = new Random();
	}
	
	public InteractiveObject selectItem (List<InteractiveObject> eo2){

		int ammount = eo2.size();
		int catche = 0;
		List<Integer> dump = new ArrayList<Integer>();
		List<Integer> low = new ArrayList<Integer>();
	        List<Integer> high = new ArrayList<Integer>();
	    
		for (int i = 0; i < ammount ; i ++){
			 
			 dump.add(eo2.get(i).getRarity() );
			 low.add(catche + 1);
			 catche += eo2.get(i).getRarity();
			 high.add(catche);
		}
		
		int pick = rand.nextInt(catche) + 1;
		int ii;

		 
		 for (ii = 0; ii < dump.size(); ii ++ ){
			 if ( pick >= low.get(ii) && pick <= high.get(ii) ){
				 //System.out.println(eo2.get(ii).getName() );
				 return eo2.get(ii);

				 }
			 }

			  System.out.println("Error returning EnvObjects\n Total: " + catche + "\nPicked: " + pick);
			  return null;

		 }
		 
		
	}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Hey, I solved the same problem last week in a hobby project of mine :)

Here is my C++11 implementation of it:


// Select a random segment using a distribution array defining what types to create and with what probability.
// Array must be normalized before used.
//
// Example usage:
//
// std::vector<DistEntry> distribution = {
//   {55.0f,createFoot},
//   {4.0f,createArc},
//   {39.0f,createZigZag},
//   {4.0f,createSmoothDiagonal},
//   {10.0f,createBezier}
// };
//
// normalizeDistribution(distribution);
//
// Segment* segment = randomSegmentFromDistribution(nullptr, distribution);
//
Segment* randomSegmentFromDistribution(Segment* parent, const std::vector<DistEntry>& normDist)
{
  float r = drand48();
  for(auto e : normDist) {
    if(e.first >= r) {
      return e.second(parent);
    } else {
      r -= e.first;
    }
  }
  assert(0); // something went wrong, is the distribution normalized?
  return nullptr;
}


void normalizeDistribution(std::vector<DistEntry>& distribution)
{
  std::sort(std::begin(distribution), std::end(distribution));
  float sum = 0;
  for(auto& e : distribution) {
    sum += e.first;
  }
  for(auto& e : distribution) {
    e.first /= sum;
  }
}

Also supports floats in the distribution...

I'm pretty sure it works as intended, but it is easy to get confused when working with probabilities for some reason.

OK, I'll have a go. Here's a complete working tested C++11 program that chooses 10 marbles from Shippou's bag, with replacement.


#include <algorithm>
#include <iostream>
#include <random>
#include <string>
#include <utility>
#include <vector>

using namespace std;


// A bag of marbles, with colour and count.
vector<pair<string, int>> marbles = {
  { "red",     5 },
  { "green",  10 },
  { "yellow", 15 },
  { "blue",   20 }
};


int main()
{
  minstd_rand prng;
  vector<int> weights;
  transform(begin(marbles), end(marbles), back_inserter(weights),
            [](pair<string, int> const& p) { return p.second; });
  discrete_distribution<> choose(begin(weights), end(weights));

  // Choose 10 marbles, replacing them in the bag each time.
  for (int i = 0; i < 10; ++i)
  {
    cout << marbles[choose(prng)].first << "\n";
  }
}

Stephen M. Webb
Professional Free Software Developer


OK, I'll have a go. Here's a complete working tested C++11 program that chooses 10 marbles from Shippou's bag, with replacement

Oh, thanks for the <random> example, hadn't got around to looking through that one yet :)

Just an update ... that code I posted earlier has been incorporated into a map generator.

I'll attach the compiled project if ya want to poke fun at it ( Java 1.7 ) [Download LINK]

from DOS:

java -jar test.jar

N S E W to move

Q to quit

MAP to regen map

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

This topic is closed to new replies.

Advertisement