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);
     }
}