Surprised I knocked this out very quickly for me, challenge
https://www.reddit.com/r/dailyprogrammer/comments/5bn0b7/20161107_challenge_291_easy_goldilocks_bear/
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<int[]> values = new ArrayList<>();
String filePath = "someFile.txt";
try {
BufferedReader br = new BufferedReader(
new FileReader(filePath));
String currentLine;
while ((currentLine = br.readLine()) != null) {
int seatCapacity = Integer.parseInt(currentLine.
substring(0, currentLine.indexOf(' ')));
int temp = Integer.parseInt(currentLine.substring(currentLine.indexOf(' ') +1, currentLine.length()));
values.add(new int[] {seatCapacity, temp});
}
} catch (IOException ex) {
System.out.println();
}
StringBuilder suitableChairs = new StringBuilder();
int weight =0, maxTemp =0;
for (int i = 0; i < values.size(); i++) {
if (i == 0) {
weight = values.get(i)[0];
maxTemp = values.get(i)[1];
} else if (values.get(i)[0] >= weight && values.get(i)[1] <= maxTemp) {
suitableChairs.append(i + " ");
}
}
System.out.println(suitableChairs);
}
}
Wednesday, 9 November 2016
Friday, 7 October 2016
Quality again
I am trying to cultivate an attitude of logical thinking and pragmatism, in the same way the main character in zen and the art of motorcycle maintenance fixes his bike by concentrating on quality, a job done properly. In the way he came across a washer which caused numerous problems which seemed unrelated, my car had a loose drive shaft bolt which caused the following errors, adaptive suspension unavailable, abs error, traction control error, stability service required.
Due to poor workmanship from a main dealer, there is the below image.
The bolt on the right showing shiny threads where it has been cross threaded subsequently loosed due to vibration. I am not very mechanically inclined however applying a thought process of what I can see, what makes sense and applying the solution with patience worked well.
Due to poor workmanship from a main dealer, there is the below image.
The bolt on the right showing shiny threads where it has been cross threaded subsequently loosed due to vibration. I am not very mechanically inclined however applying a thought process of what I can see, what makes sense and applying the solution with patience worked well.
Monday, 3 October 2016
Learning linux
Surprisingly I've enjoyed learning a lot about BASH and some of the single use tools that just make things easy.
Editing multiple files at once, using vim, understanding what other people meant when they said ssh, making a patch file and installing packages to make it easy. Nice to also go over a lot of regex, on my list to learn but didn't really get until now.
I have also done some minor scripting which was handy for downloading multiple files from usenet to check each file for integrity. Looked something like
for i in $(ls *1.par2); do par2 r $i; done;
Still a long way to scripting, compile, and remote admin. I am now a fan of no starch press books.
On top of all of that I read Zen and art of motorcycle maintenance, which discusses in depth the idea of quality. To me the idea of quality came across as that happens when someone cares about what they are doing. Interesting ideas of being stuck the bolt which cannot be undone even with destruction as an option, that the bolt doesn't care it is what it is, that does not mean the problem is insurmountable. I have been there many times.
Editing multiple files at once, using vim, understanding what other people meant when they said ssh, making a patch file and installing packages to make it easy. Nice to also go over a lot of regex, on my list to learn but didn't really get until now.
I have also done some minor scripting which was handy for downloading multiple files from usenet to check each file for integrity. Looked something like
for i in $(ls *1.par2); do par2 r $i; done;
Still a long way to scripting, compile, and remote admin. I am now a fan of no starch press books.
On top of all of that I read Zen and art of motorcycle maintenance, which discusses in depth the idea of quality. To me the idea of quality came across as that happens when someone cares about what they are doing. Interesting ideas of being stuck the bolt which cannot be undone even with destruction as an option, that the bolt doesn't care it is what it is, that does not mean the problem is insurmountable. I have been there many times.
Sunday, 4 September 2016
Driver memory leak
An issue I've not before, machine starts to stutter, checking task manager memory usage is pinned at 99%. Sorting the processes by usage nothing untoward is shown. In the users tab it showed 4 gig for my user, so at least I knew it wasn't a process that belonged to me.
Informative posts that helped get to the bottom of it,
Poolmon allowed me to see which processes where using the memory.
The big numbers in the seventh column point to NDNB. In cmd change the working directory to C:\Windows\System32\drivers and using find,
findstr /s NDNB. Resulting in a lot of garbage text with NDU.sys in the middle.
Solution from tomshardware
SOLUTION:
Windows Network Data Usage Monitoring Driver - Windows 8 Service
This service provides network data usage monitoring functionality.
This service exists in Windows 8 only.
Startup Type
Windows 8 edition without SP
Core Automatic
Professional Automatic
Enterprise Automatic
Default Properties
Display name: Windows Network Data Usage Monitoring Driver
Service name: Ndu
Type: kernel
Path: %WinDir%\system32\drivers\Ndu.sys
Error control: normal
Default Behavior
The Windows Network Data Usage Monitoring Driver service is a kernel mode driver. If the Windows Network Data Usage Monitoring Driver fails to start, the error is logged. Windows 8 startup proceeds, but a message box is displayed informing you that the Ndu service has failed to start.
To Fix Memory Leaks on Non-Paged-Pool:
Changed the registry value instead of using Autoruns:
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Ndu
Change the Start value to 4 (for disable).
The only other issues I can see that are related to the memory leak are killer network drivers. Multiple reboots did not fix the issue.
Informative posts that helped get to the bottom of it,
Poolmon allowed me to see which processes where using the memory.
The big numbers in the seventh column point to NDNB. In cmd change the working directory to C:\Windows\System32\drivers and using find,
findstr /s NDNB. Resulting in a lot of garbage text with NDU.sys in the middle.
Solution from tomshardware
SOLUTION:
Windows Network Data Usage Monitoring Driver - Windows 8 Service
This service provides network data usage monitoring functionality.
This service exists in Windows 8 only.
Startup Type
Windows 8 edition without SP
Core Automatic
Professional Automatic
Enterprise Automatic
Default Properties
Display name: Windows Network Data Usage Monitoring Driver
Service name: Ndu
Type: kernel
Path: %WinDir%\system32\drivers\Ndu.sys
Error control: normal
Default Behavior
The Windows Network Data Usage Monitoring Driver service is a kernel mode driver. If the Windows Network Data Usage Monitoring Driver fails to start, the error is logged. Windows 8 startup proceeds, but a message box is displayed informing you that the Ndu service has failed to start.
To Fix Memory Leaks on Non-Paged-Pool:
Changed the registry value instead of using Autoruns:
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Ndu
Change the Start value to 4 (for disable).
The only other issues I can see that are related to the memory leak are killer network drivers. Multiple reboots did not fix the issue.
Monday, 27 June 2016
Challenge #272 [Easy] What's in the bag?
Another day another challenge, I need to program a lot more as at the moment all I have been doing is studying for the OCP exam, it is harder than I had anticipated with all the functional programming. As I had thought it would be similar to linq, perhaps the understanding was not there at the time. Either way I am not practicing enough and caught up in the what if I fail stuff.
User wins $10,000 due to botched forced Windows 10 upgrade.
Properly want an LED peggy board to make a flashing mooninite sign, it would change between Ignignokt and Err.
YouTube 500 error that I actually experienced.
And on to the challenge, I look it against the other examples on daily programmer, so I have a long way to go.
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Character, Integer> fullBag = new HashMap<Character, Integer>() {{
put('A', 9); put('B', 2); put('C', 2); put('D', 4); put('E', 12);
put('F', 2); put('G', 3); put('H', 2); put('I', 9); put('J', 1);
put('K', 1); put('L', 4); put('M', 2); put('N', 6); put('O', 8);
put('P', 2); put('Q', 1); put('R', 6); put('S', 4); put('T', 6);
put('U', 4); put('V', 2); put('W', 2); put('X', 1); put('Y', 2);
put('Z', 1); put('_', 2);
}};
//String tilesToRemove = "PQAREIOURSTHGWIOAE_";
String tilesToRemove = "LQTOONOEFFJZT";
//String tilesToRemove = "AXHDRUIOR_XHJZUQEE";
for (Character tile : tilesToRemove.toCharArray()) {
if (fullBag.keySet().contains(tile)) {
fullBag.put(tile, fullBag.get(tile) -1);
}
}
boolean hasNegativeTiles = fullBag.values().stream().filter( x -> x < 0 ).limit(1).count() > 0;
if (hasNegativeTiles) {
List<Character> negativeTiles = new ArrayList<>();
for (Character tile : fullBag.keySet()) {
if (fullBag.get(tile) < 0) { negativeTiles.add(tile);}
}
System.out.println("Invalid input. More "
+ negativeTiles.toString().substring(1, negativeTiles.toString().length()-1)
+ " have been taken from the bag than possible.");
} else {
List<Character> charsNeeded;
Map<Integer, List<Character>> filteredMap =
new HashMap<>();
for (int i = 12; i >= 0; i-- ) {
charsNeeded = new ArrayList<>();
for (Character c : fullBag.keySet()) {
if (fullBag.get(c) == i) {
charsNeeded.add(c);
}
}
if (!charsNeeded.isEmpty()) {
filteredMap.put(i, charsNeeded);
}
}
List<Integer> reversedList = new ArrayList<>(filteredMap.keySet());
Collections.reverse(reversedList);
for (Integer key : reversedList) {
String collectionToPrint = filteredMap.get(key).toString();
System.out.println(key + ":\t" + collectionToPrint.substring(1, collectionToPrint.length() -1));
}
}
}
}
User wins $10,000 due to botched forced Windows 10 upgrade.
Properly want an LED peggy board to make a flashing mooninite sign, it would change between Ignignokt and Err.
YouTube 500 error that I actually experienced.
And on to the challenge, I look it against the other examples on daily programmer, so I have a long way to go.
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Character, Integer> fullBag = new HashMap<Character, Integer>() {{
put('A', 9); put('B', 2); put('C', 2); put('D', 4); put('E', 12);
put('F', 2); put('G', 3); put('H', 2); put('I', 9); put('J', 1);
put('K', 1); put('L', 4); put('M', 2); put('N', 6); put('O', 8);
put('P', 2); put('Q', 1); put('R', 6); put('S', 4); put('T', 6);
put('U', 4); put('V', 2); put('W', 2); put('X', 1); put('Y', 2);
put('Z', 1); put('_', 2);
}};
//String tilesToRemove = "PQAREIOURSTHGWIOAE_";
String tilesToRemove = "LQTOONOEFFJZT";
//String tilesToRemove = "AXHDRUIOR_XHJZUQEE";
for (Character tile : tilesToRemove.toCharArray()) {
if (fullBag.keySet().contains(tile)) {
fullBag.put(tile, fullBag.get(tile) -1);
}
}
boolean hasNegativeTiles = fullBag.values().stream().filter( x -> x < 0 ).limit(1).count() > 0;
if (hasNegativeTiles) {
List<Character> negativeTiles = new ArrayList<>();
for (Character tile : fullBag.keySet()) {
if (fullBag.get(tile) < 0) { negativeTiles.add(tile);}
}
System.out.println("Invalid input. More "
+ negativeTiles.toString().substring(1, negativeTiles.toString().length()-1)
+ " have been taken from the bag than possible.");
} else {
List<Character> charsNeeded;
Map<Integer, List<Character>> filteredMap =
new HashMap<>();
for (int i = 12; i >= 0; i-- ) {
charsNeeded = new ArrayList<>();
for (Character c : fullBag.keySet()) {
if (fullBag.get(c) == i) {
charsNeeded.add(c);
}
}
if (!charsNeeded.isEmpty()) {
filteredMap.put(i, charsNeeded);
}
}
List<Integer> reversedList = new ArrayList<>(filteredMap.keySet());
Collections.reverse(reversedList);
for (Integer key : reversedList) {
String collectionToPrint = filteredMap.get(key).toString();
System.out.println(key + ":\t" + collectionToPrint.substring(1, collectionToPrint.length() -1));
}
}
}
}
Monday, 13 June 2016
Passed Java OCA Programmer 1 1Z0-808!!!
Passed, it took a significant amount of work and hopefully I now have the confidence to build more of my own things. To avoid that I did a programming challenge.
What did help on the exam is the enthuware tests, lots of unique questions with the tougher items having in depth descriptions. I liked the Jeanne Boyarsky and Scott Selikoff study guides, they do keep track of errata.
Having made a start, I am now thinking 3 months is optimistic if I am to include practice exams, jpassion, and other exam preparation. It is exciting as there are more interesting language features in the OCP exam, steams, lambdas, generics, and concurrency. They are a lot more fun than how many ways can the examiner confuse me with implicit type casting and chaining string methods.
I also need to keep my eye on the main goal of getting a job as a developer rather than just passing an exam, I have some ideas for my own projects.
There is a lot of doubt, as it is easy to give up where being a developer relies on patience, persistence, and methodical thought which if I am can get that down it would improve much more than my development career.
Pacman walk-through!
Challenge to transpose text,
What I did notice from the solutions on reddit is that they are all different to each other including mine, although I do not agree with the solution using exceptions as program flow.
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String line, EOF = "-1";
List<String> lines = new ArrayList<>();
boolean hasNextLine;
do {
line = keyboard.nextLine();
hasNextLine = !line.equals(EOF);
if (hasNextLine) {
lines.add(line);
}
} while (hasNextLine);
int rows = 0;
for (String aline : lines) {
if (rows < aline.length()) rows = aline.length();
}
int cols = lines.size();
char[][] charGrid = new char[rows][cols];
for (char[] row : charGrid) {
for( int i = 0; i < row.length; i++) { row[i] = ' '; }
}
for ( int i = 0; i < lines.size(); i++) {
for (int j = 0; j < lines.get(i).length(); j++) {
charGrid[j][i] = lines.get(i).charAt(j);
}
}
for (char[] lineOfChars : charGrid) {
System.out.println(new String(lineOfChars));
}
}
}
What did help on the exam is the enthuware tests, lots of unique questions with the tougher items having in depth descriptions. I liked the Jeanne Boyarsky and Scott Selikoff study guides, they do keep track of errata.
Having made a start, I am now thinking 3 months is optimistic if I am to include practice exams, jpassion, and other exam preparation. It is exciting as there are more interesting language features in the OCP exam, steams, lambdas, generics, and concurrency. They are a lot more fun than how many ways can the examiner confuse me with implicit type casting and chaining string methods.
I also need to keep my eye on the main goal of getting a job as a developer rather than just passing an exam, I have some ideas for my own projects.
There is a lot of doubt, as it is easy to give up where being a developer relies on patience, persistence, and methodical thought which if I am can get that down it would improve much more than my development career.
Pacman walk-through!
Challenge to transpose text,
What I did notice from the solutions on reddit is that they are all different to each other including mine, although I do not agree with the solution using exceptions as program flow.
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String line, EOF = "-1";
List<String> lines = new ArrayList<>();
boolean hasNextLine;
do {
line = keyboard.nextLine();
hasNextLine = !line.equals(EOF);
if (hasNextLine) {
lines.add(line);
}
} while (hasNextLine);
int rows = 0;
for (String aline : lines) {
if (rows < aline.length()) rows = aline.length();
}
int cols = lines.size();
char[][] charGrid = new char[rows][cols];
for (char[] row : charGrid) {
for( int i = 0; i < row.length; i++) { row[i] = ' '; }
}
for ( int i = 0; i < lines.size(); i++) {
for (int j = 0; j < lines.get(i).length(); j++) {
charGrid[j][i] = lines.get(i).charAt(j);
}
}
for (char[] lineOfChars : charGrid) {
System.out.println(new String(lineOfChars));
}
}
}
Monday, 6 June 2016
Dodge viper parked on my street!
And after the excitement I have booked my Java OCA exam for Thursday July 7th, from the mocks it is looking good, some concern over how useful they will be however I would like something / someone else to say hey look this guy can do something. I do have some small ideas for programs to help build up even a small portfolio. Then again might get called on invert a binary tree or something.
Been having some minor issues with VLC player moving off screen and windows key left right would not move it alt + space, then m, arrow keys to move the window to where you want.
TedX how to learn anything the first 20 hours.
Seems a shame most java developers are only really using catch statements for debugging and logging although recovery can be complicated.
Good discussion on hacker news around two factor authentication and google, to be fair it is a social attack that has happened.
Free book on building problem solvers, added to the reading pile.
Tuesday, 24 May 2016
Doom tweak and articles
As I am quite keen on the Doom2016 multiplayer the tweak that has worked well for me on moue smoothing, removing the startup videos, and start in multiplayer mode. Open your steam library / second click on DOOM / properties / general tab / set launch options / set as "+com_gameMode 2+com_skipIntroVideo 1+set m_smooth 0+com_skipKeyPressOnLoadScreens 1" without the quotation marks. Strange that it contains spaces but is functional.
Developers can have a life outside of coding, which is good to know.
IEEE article about the use of body cameras, some of it makes sense the part around speed cameras I am not convinced as the last article I read about them was that a number of UK stats did not include regression to the mean regarding the frequency of accidents post camera installation.
Vector is a synonym for a one dimension array in programming.
For Java bits and pieces, packaging up apps with jar can be a pain I do find the class path a bit hard to get my head around, 7zip is handy for opening jar files. And after all of that and feeling crazy, line break is the delimiter for commands in the manifest so I was typing Main-class: aPackage.Main where I needed
Main-class: aPackage.Main new line!
Developers can have a life outside of coding, which is good to know.
IEEE article about the use of body cameras, some of it makes sense the part around speed cameras I am not convinced as the last article I read about them was that a number of UK stats did not include regression to the mean regarding the frequency of accidents post camera installation.
Vector is a synonym for a one dimension array in programming.
For Java bits and pieces, packaging up apps with jar can be a pain I do find the class path a bit hard to get my head around, 7zip is handy for opening jar files. And after all of that and feeling crazy, line break is the delimiter for commands in the manifest so I was typing Main-class: aPackage.Main where I needed
Main-class: aPackage.Main new line!
Thursday, 19 May 2016
Doom makes my graphics card hot
The temps are a little high at the moment, back of the card running at 60c, which seems a little hot. With the case closed nothing seems happy. Thinking of moving the graphics card down a couple of slots as between the card and the CPU is the m.2 drive.
Note: there is space between the cooler and memory just a limited amount.
Getting there with the Java OCA mocks, knocked out 79%, pass rate is 65. Getting that booked soon.
Actually liking the book think like a programmer by Sprual, he does have a youtube series which has extra content, very handy as I thought I was alone in finding it hard just to break problems down which requires practice.
Another guy I found this week, funfunfunction youtube channel, easy to follow for breaking down complex issues, he seems to mostly do java script and easy to follow.
Note: there is space between the cooler and memory just a limited amount.
Getting there with the Java OCA mocks, knocked out 79%, pass rate is 65. Getting that booked soon.
Actually liking the book think like a programmer by Sprual, he does have a youtube series which has extra content, very handy as I thought I was alone in finding it hard just to break problems down which requires practice.
Another guy I found this week, funfunfunction youtube channel, easy to follow for breaking down complex issues, he seems to mostly do java script and easy to follow.
Sunday, 8 May 2016
Getting linux working is harder than it looks
It is harder than it looks, my idea would be to have a persistent install on USB stick which then some bios boot order fiddling, plug in stick boot Linux or no stick boot windows.
What I wish I knew then, Ubuntu can actually have its boot loader on the motherboard because of how UEFI works which is all new to me, I hope I have that right. So I thought I had broken my windows install for a while as no OS found. It is in the bios to change between the different types. After all of that secure boot needs to be turned off.
Solution which worked best for me has been hyper V, selecting a gen 2 machine having added a graphics card and networking makes it much more useful. The networking takes a bit of fiddling as it has to be set to use a switch with external access, assuming network access is required.
Ubuntu after all of this was giving me a hard time lots of scrolling error messages, SUSE worked just as is, it only complains about the pci not having any configurable space.
I am quite happy playing with the terminal, handy tip which would have been useful to me years ago, when video files used to be shared in multiple parts you can join them together with the cat command unlike my erm friend who would play each file in turn.
What I wish I knew then, Ubuntu can actually have its boot loader on the motherboard because of how UEFI works which is all new to me, I hope I have that right. So I thought I had broken my windows install for a while as no OS found. It is in the bios to change between the different types. After all of that secure boot needs to be turned off.
Solution which worked best for me has been hyper V, selecting a gen 2 machine having added a graphics card and networking makes it much more useful. The networking takes a bit of fiddling as it has to be set to use a switch with external access, assuming network access is required.
Ubuntu after all of this was giving me a hard time lots of scrolling error messages, SUSE worked just as is, it only complains about the pci not having any configurable space.
I am quite happy playing with the terminal, handy tip which would have been useful to me years ago, when video files used to be shared in multiple parts you can join them together with the cat command unlike my erm friend who would play each file in turn.
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.
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
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()
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.
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.
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.
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.
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.
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();
}
}
}
}
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.
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'));
}
}
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'));
}
}
Subscribe to:
Posts (Atom)