Sunday, 22 November 2015

Update to lego thing as well

Link to MIT algorithms course, bought a book then omg this is hard.

Listening to podcasts https://codecombat.com/ came up, actually looks fun but bad memories of javascript under pressure.

I had another go at the lego picture maker, does seem to have a tendency to make the colours purple for some reason. Also IntStream just makes some of this stuff so easy.

Once it is in a better state I would like to get it on github. I get a bit hung up about poor code, I come back to it weeks later with wtf was I thinking. Need to add a front end, accept different input and output file types, and those actual lego nubs. 

Must get away from magic numbers. 

public static int[] getLegoColourEquiv(int[] rgb) {
    int[] returnColourRGB = {1,2,3};    
    if(rgb == null) {
        return
returnColourRGB;
    }
    int rgbAverage = IntStream.of(rgb).sum() / rgb.length;
    int gapFromColour = Integer.MAX_VALUE;
    int colourAverage;
    int rgbDiff;

    for (int[] colour : colours) {
        colourAverage = IntStream.of(colour).sum() / colour.length;
        rgbDiff = rgbAverage - colourAverage ;
        if(rgbDiff < 0) { rgbDiff *= -1;}
        if(rgbDiff < gapFromColour) {
            gapFromColour = rgbDiff;
            returnColourRGB = Arrays.copyOf(colour, colour.length);
        }
    }
    return returnColourRGB;
}

Wednesday, 18 November 2015

Messy code which was fun to write

Some bits this week

cmd quser says when the user logged on, handy for when the boss asks why I am packing up so early, because I got here early :) 

Found what looks like a good book, The Icarus Deception: How High Will You Fly?

rainforestQA awesome to have that many testers on standby. 

Good pod cast, software engineering daily.

At the moment I like the idea of getting a laptop with a Linux on to play with even if it is dual boot.

So here is a mess but it works, trying to write a program that turns an image into lego blocks. 

 package com.company;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

public class LegoPictureMaker {
    public String filePath;
    public BufferedImage img;
    public int legoSquareSideLength;

    public LegoPictureMaker(String filePath) {
        this.legoSquareSideLength = 16;
        this.filePath = filePath;
    }

    public void makeImage() {
        System.out.println("Grabbing file...");
        img = grabFile();
        System.out.println("Processing lego blocks");
        processFile();
        System.out.println("Done!");
    }

    //process file
    private void processFile() {

        //work out of squares needed in width and height
        int xTiles = img.getRaster().getWidth() / legoSquareSideLength;
        int yTiles = img.getRaster().getHeight() / legoSquareSideLength;

        //build image I can write to
        BufferedImage buildImage;
        buildImage = new BufferedImage(
                (xTiles * legoSquareSideLength),
                (yTiles * legoSquareSideLength),
                 BufferedImage.TYPE_INT_RGB);

        int totalTiles = xTiles * yTiles;
        int red= 0, green = 0, blue = 0;
        int[] testArray = new int[3];
        img.getRaster().getPixel(0,0, testArray);

        //make something usable
        WritableRaster writableRaster = (WritableRaster)buildImage.getData();
        int[][][] averageColour = new int[xTiles][yTiles][3];
        for(int x = 0; x < xTiles; x++) {
            for (int y = 0; y < yTiles; y++) {
                averageColour[x][y] = getAverageColour(x * legoSquareSideLength, y * legoSquareSideLength);
                writeTileColour(writableRaster, x * legoSquareSideLength, y * legoSquareSideLength, averageColour[x][y]);
            }
        }
        saveImage(buildImage, writableRaster);
    }

    private void writeTileColour(WritableRaster writableRaster, int xPoint, int yPoint, int[] rgbValues) {
        int endX = xPoint + legoSquareSideLength;
        int endY = yPoint + legoSquareSideLength;
        for (int x = xPoint; x < endX; x++) {
            for (int y = yPoint; y < endY; y++) {
                writableRaster.setPixel(x, y, rgbValues);
            }
        }
    }

    private int[] getAverageColour(int xPoint, int yPoint) {
        int red= 0, green = 0, blue = 0;
        int endX = xPoint + legoSquareSideLength;
        int endY = yPoint + legoSquareSideLength;
        int[] testArray = new int[3];;

        for (int i = xPoint; i < endX; i++) {
            for (int j = yPoint; j < endY; j++) {
                img.getRaster().getPixel(i,j, testArray);
                red += testArray[0];
                green += testArray[1];
                blue += testArray[2];
            }
        }
        int amountOfPixels = legoSquareSideLength * legoSquareSideLength;
        return new int[] {  red / amountOfPixels,
                            green / amountOfPixels,
                            blue / amountOfPixels};
    }

    //save image
    public void saveImage(BufferedImage buildImage, WritableRaster writableRaster) {
        //save and close file
        buildImage.setData(writableRaster);
        File outputFile = new File("testest.png");
        try {
            ImageIO.write(buildImage, "png", outputFile);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //get the file
    public BufferedImage grabFile() {
        BufferedImage img = null;

        if (filePath != null && !filePath.isEmpty()) {
            try {
                img = ImageIO.read(new File(this.filePath));
            } catch (IOException ex) {
                System.out.println("broke here");
                ex.printStackTrace();
            }
        }
        return img;
    }
}

Wednesday, 11 November 2015

Challenge where I got stuck

Annoyed something so simple took this long and still doesn't bloody work correctly, waaah!

 package com.company;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class PasswordGame {
    public String[] guessWords;
    public String password;
    enum difficultySettings {VERY_EASY, EASY, MEDIUM, HARD, VERY_HARD}
    difficultySettings difficulty;
    public int amountOfGuesses;

    public PasswordGame(difficultySettings aDifficulty) {
        this.difficulty = aDifficulty;
        getGuessWordsAndPassword(difficulty);
    }

    public void gameRun() {
        System.out.println("You have " + amountOfGuesses + " guess");
        System.out.println("Your word list: ");
        printWordList();
        boolean gameWon = false;
        String wordGuess;
        System.out.println("Password is: " + this.password);
        while (!gameWon && amountOfGuesses > 0) {
            wordGuess = getGuess();
            if (wordGuess.equals(password)) {
                gameWon = true;
            } else {
                amountOfGuesses--;
                System.out.println("Unlucky: " + passwordCompare(wordGuess) + " guesses left: " + amountOfGuesses);
            }
        }

        if (gameWon) {
            System.out.println("You WIN!!!");
        } else {
            System.out.println("You lose :(");
        }
    }

    private String passwordCompare(String wordGuess) {
        int correctChar = 0;
        int correctCharAndPlace = 0;
        ArrayList<Character> passWordCopy = new ArrayList<>();
        for (char aChar : password.toCharArray()) { passWordCopy.add(aChar); }
        ArrayList<Character> guess = new ArrayList<>();
        for (char aChar : wordGuess.toUpperCase().toCharArray()) { guess.add(aChar); }

        for(int i = 0; i < guess.size() && i < passWordCopy.size(); i++) {
            if (guess.get(i) == passWordCopy.get(i)) {
                correctChar++; correctCharAndPlace++;
            } else if ( passWordCopy.contains(guess.get(i))) {
                correctChar++;
                passWordCopy.set(i, '+');
            }
        }


        return "correct chracter: " + correctChar + " and in the correct place: " + correctCharAndPlace;
    }

    private String getGuess() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String wordGuessed = "";
        try {
            wordGuessed = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return wordGuessed;
    }

    private void printWordList() {
        for (String word : guessWords) {
            System.out.println(word);
        }
    }

    public String[] getGuessWordsAndPassword(difficultySettings aDifficulty) {
        switch (aDifficulty) {
            case VERY_EASY:
                amountOfGuesses = 20;
                populateWordsAndPassWord(10,5);
                break;
            case EASY:
                amountOfGuesses = 15;
                populateWordsAndPassWord(10,6);
                break;
            case MEDIUM:
                amountOfGuesses = 12;
                populateWordsAndPassWord(10,7);
                break;
            case HARD:
                amountOfGuesses = 10;
                populateWordsAndPassWord(10,8);
                break;
            case VERY_HARD:
            default:
                amountOfGuesses = 8;
                populateWordsAndPassWord(10,9);
                break;
        }

        return new String[]{};
    }

    private void populateWordsAndPassWord(int wordLength, int amountOfWords) {
        ArrayList<String> filteredList = this.filteredWordList(wordLength, amountOfWords);
        Collections.shuffle(filteredList);
        this.guessWords = filteredList.toArray(new String[filteredList.size()]);
        this.password = guessWords[new Random().nextInt(this.guessWords.length)];
    }

    private ArrayList<String> filteredWordList(int wordLength, int amountOfwords) {
        FileReader fileReader;
        BufferedReader bufferedReader;
        Set<String> wordSet = new HashSet<>(); //set to filter duplicates
        try {
            fileReader = new FileReader("someplace\\enable1.txt");
            bufferedReader = new BufferedReader(fileReader);
            String word;
            while ((word = bufferedReader.readLine()) != null) {
                if(word.length() == wordLength) {
                    wordSet.add(word);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        ArrayList<String> words = new ArrayList<>(wordSet);
        ArrayList<String> sizedWords = new ArrayList<>();

        for (int i = 0; i < amountOfwords; i++) {
            sizedWords.add(words.get(i).toUpperCase());
        }
        return sizedWords;
    }
}

Tuesday, 10 November 2015

Short one

I went over board on an intermediate challenge so put off doing a post. 

Links for much happiness,

http://12factor.net/
http://www.sunjw.us/jstoolnpp/ js tool, good plugin for notepad++
https://skillsmatter.com/ guys at work talking about clojure came across skills matter, over £2k to listen to uncle bob!

Got quite into evernote, beats the bits of paper I always lose by a large margin. 

Since I am studying for the Java 8 OCA, http://enthuware.com/index.php apparently is the thing to do, the exam does seem quite pedantic to me but that also shows how dependent I am on autocomplete.

Sunday, 1 November 2015

Windows 10 start button not working and I also did a programming challenge

On windows 10 and needed some anti virus, installed Kaspersky, windows key no longer works and cannot click on any of the buttons except shortcuts. I may need another way of getting to applications other than win key and type.

Solution: https://www.techmesto.com/fix-start-menu-broken-windows-10-technical-preview/ 

Or run this in power shell
Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage 
-DisableDevelopmentMode 
-Register "$($_.InstallLocation)\AppXManifest.xml"}
 
Challenge 238 Easy consonants and vowels

package com.company;
import java.util.Random;
import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
       String inputString = "CVcvcvcc";
        char[] consonants = "bcdfghjklmnpqrstvwxyz".toCharArray();
        char[] vowels = "aeiou".toCharArray();
        Random random = new Random();
        Pattern pattern = Pattern.compile("[^vcVC]");
        Matcher matcher = pattern.matcher(inputString);

        if (matcher.find()) {
            System.out.println("Invalid character in input");
        } else {
            StringBuilder output =  
            new StringBuilder(inputString.length());
            for (char letter : inputString.toCharArray()) {
                switch (letter) {
                    case 'c':
                      output.append(consonants[random.nextInt
                      (consonants.length)]);
                      break;
                    case 'C':
                      output.append(Character.toUpperCase 
                      (consonants[random.nextInt(consonants.length)]));
                      break;
                    case 'V':
                      output.append(Character.toUpperCase 
                      (vowels[random.nextInt(vowels.length)]));
                      break;
                    case 'v':
                      output.append(vowels[random.nextInt
                      (vowels.length)]);
                      break;
                }
            }
            System.out.println(output);
        }
    }
}
 
Originally did this with multiple ifs' and it looked bloody awful.