Monday, January 4, 2021

Showing how virtual methods & inheritance work in C++

#include<iostream>

using namespace std;

class Base {
   public: virtual void f() { cout << "Base" << endl; }
};

class D1 : public Base {
   void f() { cout << "D1" << endl; }
};

class D2 : public Base { 
   void f() { cout << "D2" << endl; } 
};

void pointer(Base *b)    { b->f(); }
void reference(Base &b)  { b.f();  }
void base(Base b)        { b.f();  }

#define test_pointer(x)   cout << "pointer   " #x << ": "; pointer(x);
#define test_reference(x) cout << "reference " #x << ": "; reference(x);
#define test_base(x)      cout << "base      " #x << ": "; base(x);

void test_objects() {
    cout << "-- test_objects --" << endl;
    D1 d1;
    D2 d2;
    
    test_pointer(&d1); test_pointer(&d2);   // D1 D2
    test_reference(d1); test_reference(d2); // D1 D2
    test_base(d1); test_base(d2);           // Base Base
}

void test_pointer_to_base_class() {
    cout << "-- test_pointer_to_base_class --" << endl;
    Base *pd1 = new D1();
    Base *pd2 = new D2();
    
    test_pointer(pd1); test_pointer(pd2);       // D1 D2
    test_reference(*pd1); test_reference(*pd2); // D1 D2
    test_base(*pd1); test_base(*pd2);           // Base Base
    
    delete pd1;
    delete pd2;
}

void test_pointer_to_class() {
    cout << "-- test_pointer_to_class --" << endl;
    D1 *pd1 = new D1();
    D2 *pd2 = new D2();
    
    test_pointer(pd1); test_pointer(pd2);       // D1 D2
    test_reference(*pd1); test_reference(*pd2); // D1 D2
    test_base(*pd1); test_base(*pd2);           // Base Base

    delete pd1;
    delete pd2;
}

int main()
{
    test_objects();
    test_pointer_to_base_class();
    test_pointer_to_class();
}


Expected output:
-- test_objects --
pointer   &d1: D1
pointer   &d2: D2
reference d1: D1
reference d2: D2
base      d1: Base
base      d2: Base
-- test_pointer_to_base_class --
pointer   pd1: D1
pointer   pd2: D2
reference *pd1: D1
reference *pd2: D2
base      *pd1: Base
base      *pd2: Base
-- test_pointer_to_class --
pointer   pd1: D1
pointer   pd2: D2
reference *pd1: D1
reference *pd2: D2
base      *pd1: Base
base      *pd2: Base


See it working here

Other entries:

Saturday, March 14, 2020

isPrime recursive


#include <iostream>
using namespace std;

int increments[] = { 2, 4 };

// Already beyond the square root? -> true (prime)
// (else)
// Divisible by current divisor?   -> false (not prime)
// (else)
// Calculate next divisor and recurse
bool isPrime(int n, int divisor, int incr) {
   return (divisor * divisor > n ) || 
          ( (n % divisor != 0) && 
            isPrime(n, divisor + incr, increments[incr == 2] )
          );
}
 
bool isPrime(int n) {
    return isPrime(n, 2, 1);
}

int main()
{
    for(int i = 2; i <= 100; i++ ) {
        if( isPrime(i) ) {
            cout << i << " ";
        }
    }
    cout << endl;

    return 0;
}

Other entries:

Sunday, March 1, 2020

Generate random numbers without repetition

Instead of controlling the repetition by inserting the already-generated-number in a set, create the set first, pick from there, and remove it for the next iteration,

e.g.:


import java.util.Random;

public class ControlRepetitionWithoutKeepingScore {

     public static void main(String []args) {

         int choices[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
         int sz = choices.length;
         Random random = new Random();
         
         for(int i = 0; i < choices.length; i++ ) {
             int pos = random.nextInt(sz);
             print(choices[pos]);
             
             choices[pos] = choices[sz-1];
             sz--;
         }
     }
}


Other entries:

Sunday, February 16, 2020

Shuffle characters in a String (java)

Converts chars to List --> Collections.shuffle --> String.join



import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class Shuffler {

     public static void main(String []args){
        String s = "012345";
        
        for( int i = 0; i < 10; i++) {
           System.out.println(shuffle(s));
        }
     }
     
     public static String shuffle(String s) {
        List<String> chars = Arrays.asList(s.split(""));
        Collections.shuffle(chars);
        return String.join("", chars);
     }
}

Monday, August 5, 2019

isPrime, optimization 4

Check every number and keep the previosly generated primes. Use them to test the following numbers.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const int PSIZE = 150000;
int primes[PSIZE];
int sz = 0;

bool isPrime4( int x ) {
  if(x < 2) return true;

  int limit = (int) sqrt(x);
  primes[sz] = limit+1;
  for(int *p = primes; *p <= limit; p++) {
      if( x % *p == 0 ) {
          return false;
      }
  }
  assert(sz < PSIZE);
  primes[sz++] = x;
     
  return true;
}


Other entries:

isPrime, optimization 3

Divisors start in 5. Skip the divisors that are multiple of 2 or 3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
bool isPrime3( int x ) {
  if( x == 2 || x == 3) {
      return true;
  }
  
  if( x % 2 == 0 || x % 3 == 0 ) {
      return false;
  }

  int divisor = 5;
  int delta = 2;
  int limit = (int) sqrt(x);
  while( divisor <= limit ) {
        if( x % divisor == 0 ) { 
            return false;
        }
        divisor += delta;
        delta = 6 - delta;
  }
  return true;
}


Other entries: