Thursday, 21 April 2016

Challenge and some maths

Found a few bits today, trying to install ubuntu on to a usb stick just so I can try it out and get learning some command line, having to burn a DVD and not having any software to do it, it is now in windows. Click on the iso image file in the explorer ribbon there are options to mount or burn to disc, very handy. 

The maths, frustrating that java does not have a function to use log in a base you choose however it does have natural log where it is then possible to get the needed result by dividing the natural log of some value by natural log of some base.

Math.log(x) / Math.log(2)

The challenge is about calculating shannon entropy. Which returns the correct results to at least five decimal places and got to try some streaming.

Entropy of "122333444455555666666777777788888888" is 2.7942086837942446
Entropy of "563881467447538846567288767728553786" is 2.7942086837942446
Entropy of "https://www.reddit.com/r/dailyprogrammer" is 4.056198332810095
Entropy of "int main(int argc, char *argv[])" is 3.8667292966721747

package com.company;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
public class Main {

    public static void main(String[] args) {
        String[] inputSequences  = {
                "122333444455555666666777777788888888",
                "563881467447538846567288767728553786",
                "https://www.reddit.com/r/dailyprogrammer",
                "int main(int argc, char *argv[])"
        };

        double result;
        int minimumDecimalPlaces = 5;
        String resultStringDP;
        for (String input : inputSequences) {
            result = calculateEntropy(input);
            resultStringDP = new String(result + "").split(("\\."))[1];
            if( resultStringDP.length() < minimumDecimalPlaces) {
                result = new BigDecimal(result).round(new MathContext(minimumDecimalPlaces)).doubleValue();
            }
            System.out.println("Entropy of \"" + input + "\" is " + result);
        }
    }

    public static double calculateEntropy(String input) {
        List<Double> entropyValuesPerChar = new ArrayList<>(input.length());
        List<Integer> frequencyOfChars = new ArrayList<>();
        // get unique chars
        HashSet<Character> uniqueChars = new HashSet<>(input.length());
        for ( int i = 0; i < input.length(); i++) {
            uniqueChars.add(input.charAt(i));
        }
        // for each char determine frequency and add to counter
        int count;
        for ( char uniqueLetter : uniqueChars) {
            count = 0;
            for ( char letter : input.toCharArray()) {
                if (letter == uniqueLetter) {
                    count++;
                }
            }
            frequencyOfChars.add(count);
        }

        for ( Integer freq : frequencyOfChars) {
            double x = (double)freq / input.length();
            entropyValuesPerChar.add(
                    -(x) * (Math.log(x) / Math.log(2))
            );
        }
        return entropyValuesPerChar.stream()
.mapToDouble(w -> w).sum();
    }
}

Monday, 14 March 2016

Trying to be clever

Since I have struggling so much with the Java 8 OCA I have trying to think laterally, how can I make myself a little brighter and improve my concentration. A lot of places list the usual get enough sleep, eat well etc, which is hard so I bought a guitar. Awaiting the cable to drive signal to the PC where I can learn to play through a game called Rocksmith. I've been impressed by the 60 day videos of gamers going from not picked up a guitar to knocking out paint it black at near perfect. The other site I have found useful is justinGuitar.

black electric guitar

The other things I am trying in my time off are pomodoro, I did not give the method a chance however with more time available I am willing to try it out for learning Java to take the OCA exam. The fitness thing is a tough one, fitbit has now been repaired and on route so at least I can get tracking my activity again.

Brushing up a Java a highly rated book was Exercises for programmers by Brian Hogan, it is similar to the daily programmer challenges with more of emphasis on learning, here is a task go make something, which is what I like. 

A5 size book with white cover and blue text

For Java learning I need something a little more in depth for what is used in industry, JPassion looks good for learnng as well as the London Java user group that is available remotely called JUG.

Friday, 4 March 2016

Bored and tic tac toe

Trying out of the work interview questions and knocked a simple text input tic tac toe game in 30 minutes ish. No problem I thought a simple front end and good to go, this took me a while but I finished, working on something for 10 minutes and getting distracted is not worth it.

intellij background with running tic tac toe program


package com.company;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;

public class TicTacToe {

    JButton[][] gameButtons;
    private char gameChar = 'X';
    private enum gameStatus {IN_PROGRESS, WON, DRAW}
    GameButton button = new GameButton();

    public TicTacToe() {
        //setup buttons
        gameButtons = new JButton[3][3];

        for (JButton[] row : gameButtons) {
            for (int i = 0; i < row.length; i++) {
                row[i] = new JButton();
            }
        }
    }

    public void startGame() {
        loadFrontEnd();
    }

    private void loadFrontEnd() {
        JFrame jframe = new JFrame("Tic Tac Toe");
        JPanel outer = new JPanel();
        outer.setLayout(new GridLayout(3, 3, 10, 10));

        for (JButton[] row : gameButtons) {
            for (JButton aButton : row) {
                aButton.addActionListener(button);
                outer.add(aButton);
            }
        }
        outer.setPreferredSize(new Dimension(300, 300));

        jframe.add(outer);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.pack();
        jframe.setVisible(true);
    }

    public char getAndFlipGameChar() {
        gameChar = gameChar == 'X' ? 'O' : 'X';
        return gameChar;
    }

    public gameStatus getGameStatus() {
        //check horizontal
        for (JButton[] row : gameButtons) {
            if (row[0].getText() != "") {
                if ((row[0].getText().equals(row[1].getText())) && row[0].getText().equals(row[2].getText()))
                    return gameStatus.WON;
            }
        }

        //check vertical
        for (int i = 0; i < gameButtons.length; i++) {
            if (gameButtons[0][i].getText() != ""
                    &&(gameButtons[0][i].getText().equals(gameButtons[1][i].getText()))
                    && (gameButtons[2][i].getText().equals(gameButtons[0][i].getText())))
                return gameStatus.WON;
        }

        //check diagonal
        if ( gameButtons[0][0].getText() != ""
                && (gameButtons[0][0].getText().equals(gameButtons[1][1].getText()))
                && (gameButtons[0][0].getText().equals(gameButtons[2][2].getText())))
            return gameStatus.WON;

        if ( gameButtons[2][0].getText() != ""
                && (gameButtons[0][2].getText().equals(gameButtons[1][1].getText()))
                && (gameButtons[0][2].getText().equals(gameButtons[2][0].getText())))
            return gameStatus.WON;
        //check no empties
        ArrayList<JButton> buttonList = new ArrayList<>(9);
        for (JButton[] row : gameButtons) {
            Collections.addAll(buttonList, row);
        }
        buttonList.removeIf( a -> a.getText() != "");

        if (!buttonList.isEmpty())
            return gameStatus.IN_PROGRESS;
        else
            return gameStatus.DRAW;
    }

    private void resetGame() {
        for (JButton[] row : gameButtons) {
            for (JButton aButton : row) {
                aButton.setText("");
            }
        }
    }

    class GameButton implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            JButton theButtonPressed = (JButton) e.getSource();
            // if button not used write text to it
            if (theButtonPressed.getText().equals("") && getGameStatus() == gameStatus.IN_PROGRESS ) {
                theButtonPressed.setText( Character.toString(getAndFlipGameChar()));
            }

            gameStatus currentStatus = getGameStatus();
            if (currentStatus != gameStatus.IN_PROGRESS) {
                String conclusionMessage = currentStatus == gameStatus.WON ? gameChar + " won the game!" : "DRAW!!!";
                JOptionPane.showMessageDialog(new JFrame(), conclusionMessage);
                resetGame();
            }
        }
    }
}

Monday, 29 February 2016

Atbash

Getting better at the typing, new keyboard helps as it forces me to type inline with the guide no right hand b key. I now understand the support tipping the keyboard away significantly, raising the wrists makes that bit easier on the fingers for QWE and POI keys. A bit slow unless I am in the mood for it. 


black split keyboard with chicklet keys



Had a go at the atbash challenge for daily programmer, in my opinion they just look up the algorithm then implement it in their choosen language, not the most efficient but makes sense to me.

package com.company;

public class Main {

    public static void main(String[] args) {
        String inputString = "ullyzi\n" +
                "draziw\n" +
                "/i/wzrobkiltiznnvi\n" +
                "this is an example of the atbash ZZZ cipher";

        for (char aCharacter : inputString.toCharArray()) {
            if (Character.isLetter(aCharacter)) {
                System.out.print(atBashPreserveCase(aCharacter));
            } else {
                System.out.print(aCharacter);
            }
        }
    }

    private static char atBashPreserveCase(char aCharacter) {
        if (Character.isUpperCase(aCharacter))
            return Character.toUpperCase(atBash(aCharacter));
        else
            return atBash(aCharacter);
    }

    private static char atBash(char aCharacter) {
        aCharacter = Character.toLowerCase(aCharacter);
        if (aCharacter == 'm')
            return (char) aCharacter;
        else if (aCharacter > 'm')
            return (char) ('z' - aCharacter + 'a');
        else
            return (char) ('z' - (aCharacter - 'a'));
    }
}

Saturday, 20 February 2016

Another day another challenge

Over the month I have been working on Java OCA, now scoring in the 60% after a month in the high 40 low 50s, I need to break into the 80% range before I can book the exam. 

Started to learn to touch type as one of those things I have always wanted to get around to, typing club helps. 

Talking to the developers at work about interviews, quick as you can tic tac toe, best I can do in about 30 minutes, error I noticed afterwards is it works from top left as is 0,0. 

 package com.company;

import java.util.Arrays;
import java.util.Scanner;

public class TicTacToe {
    public char[][] board;

    public TicTacToe() {
        board = new char[3][3];
        for (char[] row: board) {
            for (int i = 0; i < row.length; i++) {
                row[i] = ' ';
            }
        }
        startGame();
    }

    public void printBoard() {
        for (char[] row : board) {
            for (char letter :row) {
                System.out.print("[ " + letter + " ]" );
            }
            System.out.println();
        }
    }

    public boolean placeValue(int col, int row, char letter) {
        if (board[row][col] != ' ') {
            System.out.println("Space taken");
            return false;
        } else {
            board[row][col] = letter;
            return true;
        }
    }

    public boolean isGameWon() {

        //horizontal
        for (char[] row: board) {
            if(row[0] != ' ') {
                if (row[0] == row[1] && row[1] == row[2])
                    return true;
            }
        }

        //vertical
        for (int i = 0; i < 3; i++) {
            if (board[0][i] != ' ' && board[0][i] == board[1][i] && 

            board[1][i] == board[2][i])
                return true;
        }
        //diagonal
        if (board[0][0] != ' ' && board[1][1] == board[0][0] &&              board[1][1] == board[2][2]) return true;
        if (board[2][2] != ' ' && board[1][1] == board[0][0] && 

        board[1][1] == board[2][2]) return true;

        return false;
    }

    public void startGame() {
        String inputText = "";
        Scanner reader = new Scanner(System.in);
        printBoard();
        while (
                Arrays.asList(board).contains(' ')
                || !isGameWon()
                ) {
            System.out.println("Enter co ords and char 0 0 A: ");
            inputText = reader.nextLine().trim();
            placeValue(Integer.parseInt(String.valueOf(inputText.charAt(0))),
                    Integer.parseInt(String.valueOf(inputText.charAt(2))),
                    inputText.charAt(4));
            printBoard();
        }
        if(isGameWon()) {
            System.out.println("You Win!");
        } else {
            System.out.println("Draw!");
        }

    }
}

Monday, 1 February 2016

Challenge #249 [Easy] Playing the Stock Market

Tired after work and over thought it, then oh is that it. 

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        //String inputValues = "19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98";
        String inputValues = "9.20 8.03 10.02 8.08 8.14 8.10 8.31 8.28 8.35 8.34 8.39 8.45 8.38 8.38 8.32 8.36 8.28 8.28 8.38 8.48 8.49 8.54 8.73 8.72 8.76 8.74 8.87 8.82 8.81 8.82 8.85 8.85 8.86 8.63 8.70 8.68 8.72 8.77 8.69 8.65 8.70 8.98 8.98 8.87 8.71 9.17 9.34 9.28 8.98 9.02 9.16 9.15 9.07 9.14 9.13 9.10 9.16 9.06 9.10 9.15 9.11 8.72 8.86 8.83 8.70 8.69 8.73 8.73 8.67 8.70 8.69 8.81 8.82 8.83 8.91 8.80 8.97 8.86 8.81 8.87 8.82 8.78 8.82 8.77 8.54 8.32 8.33 8.32 8.51 8.53 8.52 8.41 8.55 8.31 8.38 8.34 8.34 8.19 8.17 8.16";
        String[] splitValues = inputValues.split(" ");
        System.out.println(Arrays.toString(splitValues));
        double[] stockTrades = new double[splitValues.length];

        for (int i = 0; i < splitValues.length; i++) {
            stockTrades[i] = Double.parseDouble(splitValues[i]);
        }

        double maxDiff = Double.MIN_VALUE, fValue = 0, lValue = 0;
        for (int i = 0; i < stockTrades.length; i++) {
            for (int j = i+2; j < stockTrades.length; j++) {
                if ((stockTrades[j] - stockTrades[i]) > maxDiff) {
                    fValue = stockTrades[i];
                    lValue = stockTrades[j];
                    maxDiff = lValue - fValue;
                }
            }
        }

        System.out.println(fValue +  " " + lValue);
    }
}


Also properly broke my lego picture maker, thank you version control! :D I did learn that with git you can check out a commit, so when I tried to commit it back to the branch, head was detached, easy way to fix. Create branch, check out new branch, commit changes, merge branches and done.

Thursday, 21 January 2016

Reverse linked list in place

Found this harder than expected as I knocked out the list in 5 minutes, reverse in place I had to look up then had the ah yeah I see moment, I did get some practice around visualising a problem.

public class MyLinkedList {
    public Node head = null;
    public Node tail = null;
   
    public void append(int valueToAdd) {
        if    (head == null && tail == null) {
            head = tail = new Node(valueToAdd);
        } else {
            tail.nextNode = new Node(valueToAdd);
            tail = tail.nextNode;
        }
    }
   
    public void printList() {
        Node aNode = head;
        while (aNode != null) {
            System.out.println(aNode.value);
            aNode = aNode.nextNode;
        }
    }
   
    public void reverse() {
        Node a = null, b = null, c = head;
        tail = head;
        while (c != null) {
            a = c.nextNode;
            c.nextNode = b;
            b = c;
            c = a;
        }
        head = b;
    }
   
    class Node {
        public int value;
        public Node nextNode = null;
      
        public Node(int valueToAdd) {
            this.value = valueToAdd;
        }
    }
}