Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Saturday, 7 January 2017

Lotto Predictions - Java AI

Hello, we want to show you simple AI algorithm and how can he produce some lotto numbers for us.

We created small algorithm, load some numbers that happen before, do some calculations and print out the next 7 numbers winning combination.

First we need to have a way to represent this sequence of 7 numbers.
For example numbers: 37, 2, 11, 15, 14, 22, 1

What we can notice immediately is that we can sort them, it doesn't matter in witch order they arrived on screen, they will still represent combination of 7 numbers. So in our case it is: 1, 2, 11, 14, 15, 22, 37

We can create simple class for that.

Helper class:

public class Numbers {
   
    private final int num1;   private final int num2;   private final int num3;
    private final int num4;   private final int num5;   private final int num6;
    private final int num7;

    public Lotto(int num1, int num2, int num3, int num4, int num5, int num6, int num7) {
        this.num1= num1;   this.num2= num2;   this.num3= num3;
        this.num4= num4;   this.num5= num5;   this.num6= num6;
        this.num7= num7;
    }
    // some getters for this numbers
}
Now we can reuse this helper class and initialize some results we already know.

First we will create some List and some maps, in list we will collect all previous result so it would be easier for us to use them and maps will be created just to remember how many points each number have.

In our case point would be how many time he was in results from before.

Using static block we will populate result list and we can start processing.

Go over result list and populate maps with numbers.
Call print prediction that will go over maps and find best matches.

Take a look at the code:

Main class:

public class Lotto {
    // here we will store all results that we know in advance
    private static List<Lotto> results = new ArrayList<Lotto>();
   
    // we will use this maps to store info for number how many times he already were in results
    private static Map<Integer, Integer> number1 = new HashMap<>();
    private static Map<Integer, Integer> number2 = new HashMap<>();
    private static Map<Integer, Integer> number3 = new HashMap<>();
    private static Map<Integer, Integer> number4 = new HashMap<>();
    private static Map<Integer, Integer> number5 = new HashMap<>();
    private static Map<Integer, Integer> number6 = new HashMap<>();
    private static Map<Integer, Integer> number7 = new HashMap<>();
   
    static { // this will load some results that already were in lottery winners
        Numbers l1 = new Numbers (2, 7, 9, 13, 14, 29, 31);
        Numbers l2 = new Numbers (8, 14, 16, 22, 27, 29, 37);
        Numbers l3 = new Lotto(12, 17, 18, 19, 26, 35, 39);
        Numbers l4 = new Lotto(4, 6, 9, 10, 11, 18, 32);
        Numbers l5 = new Lotto(2, 3, 6, 7, 10, 15, 25);
        Numbers l6 = new Lotto(13, 21, 22, 28, 30, 32, 39);
        Numbers l7 = new Lotto(9, 12, 19, 22, 28, 36, 39);
        Numbers l8 = new Lotto(11, 15, 18, 22, 24, 36, 37);
        Numbers l9 = new Lotto(4, 8, 12, 18, 19, 24, 31);
        Numbers l10 = new Lotto(4, 9, 13, 14, 17, 37, 39);
        // add values to the list          
        results.add(l1);results.add(l2);results.add(l3);results.add(l4);results.add(l5);
        results.add(l6);results.add(l7);results.add(l8);results.add(l9);results.add(l10);
       
    }
   
    // our main program
    public static void main (String [] args) {
        for (Numbers l : results) {
            addNumber(l.getNum1(), number1); addNumber(l.getNum2(), number2);
            addNumber(l.getNum3(), number3); addNumber(l.getNum4(), number4);
            addNumber(l.getNum5(), number5); addNumber(l.getNum6(), number6);
            addNumber(l.getNum7(), number7);
        }
        printPrediction();
    }

    private static void printPrediction() {
        int n1Prediction = findNumber(number1);
        int n2Prediction = findNumber(number2);
        int n3Prediction = findNumber(number3);
        int n4Prediction = findNumber(number4);
        int n5Prediction = findNumber(number5);
        int n6Prediction = findNumber(number6);
        int n7Prediction = findNumber(number7);
       
        System.out.println("Prediction for new lotto result is:");
        System.out.print("Numbers: " + n1Prediction + ", " + n2Prediction
                        + ", " + n3Prediction + ", " + n4Prediction
                        + ", " + n5Prediction + ", " + n6Prediction
                        + ", " + n7Prediction);
    }
   
    // our magic goes here
    private static int findNumber(Map<Integer, Integer> map) {
        int number = -1;
        int value = -1;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() >= value) {
                number = entry.getKey();
                value = entry.getValue();
            }
        }
        return number;
    }

    // if value exist in map then remove it and add it once again with counter + 1
    private static void addNumber(int num, Map<Integer, Integer> map) {
        if (map.containsKey(num)) {
            int exist = map.get(num).intValue();
            map.remove(num);
            map.put(num, exist + 1);
        } else {
            map.put(num, 1);
        }
    }
   
}


After running this program we get this:
Prediction for new lotto result is:
Numbers: 4, 15, 9, 22, 30, 29, 39

Why did he find that results?

He was checking witch number is most popular to happen on that place and print out that one.
Our logic is fair simple, in order to create something "smarter" you will need better algorithm for this.

Add more results, change method print prediction, count more factors not just 1 and you should get better results, and at one point hit the jackpot!

Until then, please subscribe to our blog, post some comments, like us on Facebook, share it and enjoy.

Kind regards,
M.L.


Saturday, 17 December 2016

Measure Code Speed in Java

How to measure code speed in Java

Quite often we have two solutions in our mind and we don't know which one is the best to use.
Simple way to decide that is to measure speed for executing for both code versions and use one that is faster.

So how we can actually measure the code speed? In Java it is quite easy.

You will need to recognize few key points in your code, when does it starts and when does it ends.

Before beginning your code you will add something like this:
long startTime = System.nanoTime();
This will get the current system time and put it in one variable.

At the end of code you want to measure you need to put:
long totalExecutionTime = System.nanoTime() - startTime ;
This will get current system time at the end of the code and subtract start time we created at the start of the code.

In order to see how fast is it you can just print it to console:
System.out.println("Total execution time: " + (totalExecutionTime / 1000000.0) + " ms");
This code will get the result of subtraction and divide it with 1M, this is done only to get better representation of the result we have. After we divide that, we will print the result and add "ms" at the end that we now result is in milliseconds. 1000 ms is 1 sec.

So we now know how to check the speed of our code, in order to compare it with other code you will do the same for other part:
long startTime2 = System.nanoTime();
... (code you want to measure) ...

long totalExecutionTime2 = System.nanoTime() - startTime2 ;
System.out.println("Total execution time 2: " + (totalExecutionTime2 / 1000000.0) + " ms");

Instead of just printing values you can now compare them:
if ( totalExecutionTime > totalExecutionTime2 ) {
         System.out.println("First code is faster!");
} else if ( totalExecutionTime < totalExecutionTime2 ) {
          System.out.println("Second code is faster!"); 
} else {
          System.out.println("They are equally fast!"); 
}

You can check our code example where we compare String VS String builder using this speed test: String VS StringBuilder
If this little "code" helped you, please subscribe, like us on Facebook, share it and enjoy.

Kind regards,
M.L.

Monday, 21 April 2014

Speed test: String vs StringBuilder in JAVA

We compare String with StringBuilder, run this code and see yourself, example:


public class SpeedTest
{
    public static void main(String[] args)
    {
        final String SAMPLE = "The Quick Brown Fox Jumps Over The Lazy Dog.";
        final int COUNT = 5000;

        // string
        String str = "";
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            str += SAMPLE;
        long strTotal = System.nanoTime() - start;
        if (str.length() == 123)
            System.exit(0);

        // StringBuilder
        StringBuilder builder = new StringBuilder(SAMPLE.length() * COUNT);
        start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            builder.append(SAMPLE);
        long sbTotal = System.nanoTime() - start;

        System.out.println("String total time: " + (strTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder total time: " + (sbTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder vs. String: " + (strTotal / sbTotal));
    }

}


If this little "code" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it

Have a good one. M.L.