Sets
to create a sequence of numbers

static bool isHappy (int n) {
   if(n<=0)  return false;
   Set<int> previouslySeen;
   while (n>1 && !previousySeen.contains(n)) {
      previouslySeen.add(n);
      n = completeSumOfSquaredDigits(n);
   }
   return n==1;
}

OR can do THIS:

static bool isHappy(int n) {
   if(n<=0)  return false;
   Set<int> endpoints; 
   endpoints += 1,4,16,37,58,89,145,42,20;   // comma operator makes endpoints all the numbers and only 
                                                                                //these numbers
   while(!endpoints.contains(n))  {
      n=computeSumOfSquaredDigits(n);
   }

   return n==1;
}

Structs

Let you define data structures without being all hardcore classes/object orientated programming

Exactly the same as classes except for default privacy (struct has default of public)

Farey series using struct fraction

 

static Vector<fraction> generateFareySeries(int n) {
   Set<fraction> fractions;
   for (int d=2; d<=n; d++)  {
      for(int num=1; num<d; num++ ) { 
         fraction f = {num,d};
         fraction +=f;
      }
   }   
   Vector <fraction> series;
   foreach(fraction f in fractions) series.add(f);
   return series;
}
defining a struct and overloading operators

struct fraction {
   int numerator;
   int denominator;
}

bool operator < (const fraction& one, const fraction & two)  {
   return one.numerator*two.denominator < one.denominator * two.numerator;
}

   Login to remove ads X
Feedback | How-To