Euler Problem 2

This one was incredibly straight forward again, so no real need to comment. Solution is provided below for any corrections or observations…

Euler Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

int prev = 1;
        int now = 2;
        int temp = 0;
        int total = 0;
        
        while (prev < 4000000) {
            if ((now % 2) == 0) {
                total += now;
            }
            
            temp = now + prev;
            prev = now;
            now = temp;
        }
        
        System.out.println(“Total: ” + total);

Answer: 4613732

Advertisements

Euler Programming – Problem 1

Ok, so running blogging took over from technical blogging. Something I’m going to attempt to rectify this year (a number of small steps to improve myself over the coming year hopefully).

Scanning through my Twitter stream over the Christmas break I came across an article about Euler Programming site, which provides puzzles to be solved. I’ve decided to start doing these, attempting to do at least 1 a day to try and re-activate my mind. The 1-a-day routine isn’t really succeeding at this stage though – I’ve just solved Problem 3, and this is the 10th day of January. Ah well.

I’ll attempt to post my solution to each problem, in the hope that if I’ve gone wrong, or there is a better way someone might point me in the right direction. All solutions will be done in Java.

Euler Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

My Answer

        int sum = 0;
        
        for (int i = 1; i < 1000; i++) {
            if (((i % 3) == 0) || ((i % 5) == 0)) {
                sum += i;
            }
        }
        
        System.out.println(“Sum: ” + sum);

And the overall answer is: 233168

Java XML with Betwixt

Having first being introduced to the world of parsing XML into objects in .NET a few years back, I was hooked immediately. The power of taking any stream and converting it to an object within a couple of lines of code (and then back from an object to a file / stream) was immense.

Moving into the world of Java, I can remember thinking well this will be out the box. Unfortunately it wasn’t (or at least I couldn’t find it). Just before Christmas though I stumbled across Betwixt when doing some xml parsing for another Java project. Whilst not quite as straight-forward as the .NET world, it pretty good, and I like it. I meant to blog about it back then, but didn’t get round to it. I had to do some more XML-Java parsing today, so had to refresh my memory – hence the nudge for doing this blog post.

A Simple Example

Betwixt as available from Apache Commons. After downloading and unzipping the library, it also requires a number of other Apache Common libraries in order to work – something that took me a while to figure out. I believe the other jars required are:

  • commons-beanutils.jar
  • commons-beanutils-core.jar
  • commons-digester.jar
  • commons-io.jar
  • common-logging.jar

Once these are added to our Java project, we can get on with our simple example. Its worth noting at this point that there are a few example available from the Betwixt website.

The Example XML

The example present will just be reading some XML. The XML in question looks like this:

<xml version=’1.0’?>
<locations>
   <location>home</location>
   <location>work</location>
</locations>

The POJO to Represent the XML

So first thing would be to create an object to represent out location element. This class looks like:

public class LocationBean {
   public LocationBean() {
   }

   private List location = new ArrayList<String>();

   public void setLocation(List<String> location) {
      this.location = location;
   }

   public List getLocation() {
      return location;
   }

   public void addLocation(String location) {
      this.location.add(location);
   }
}

Betwixt Configuration File for Handling Lists

In order to handle the List, we also need to create a Betwixt configuration file – something I hadn’t realised until reading this article from ‘Anonymity Re-Discovered!’ blog.

So creating this ‘LocationBean.betwixt’ file at the same level as the LocationBean class, it takes the following structure:

<?xml version='1.0' ?>
<info>
   <element name="locations">
      <element name='location' property='location' updater='addLocation' />
   </element>
</info>

Main Program Code

Finally, I now just need to implement my main java code to point the stream to the Betwixt XML Reader:

StringReader locationXml = new StringReader("<?xml version='1.0' ?><locations><location>work</location><location>home</location></locations>");
BeanReader xmlReader = new BeanReader();

try {
   xmlReader.registerBeanClass("locations", LocationBean.class);
   LocationBean markBean = (LocationBean) xmlReader.parse(locationXml);
   System.out.println("Location = " + markBean.getLocation().size());
} catch (Exception e) {
   System.out.println("Exception raised: " + e.getMessage());
}

When not handling lists, the code is a lot simpler, but I think that the example on the Betwixt site is more than adequate to cover this.

Scott Hanselman Power Tools

Ok, as per my last blog post I said I’d attempt to make myself more aware of some tools that my help to improve my productivity. As I do, I’ll attempt to give a brief review of them.

Please follow this link for Scott Hanselmans full Power Tool List.

Caveat – its likely I’ve only been using the tools for a period of a week or so – there’s a chance I don’t get on with them due to not spending enough time learning, or love them without exploring the full functionality. The likelihood though is likely to be somewhere in the middle of these 2 extremes!

LiveWriter

Love it. Using it to write this blog post. I’ve also written a number of other blog posts with it. I can remember downloading and testing a blog writer tool on Ubuntu, and this is how it should have been – that’ll be one of my tasks over Christmas to try and find something on my Ubuntu machine as competent as this.

However it’ll remain my blogging tool of choice for my works PC.

Screenshot:

image

Microsoft Live Writer

Notepad++

I’ve long been a fan of TextPad, but unlike my last 2 places of work, my current place doesn’t appear to have a licence for it. So rather than ‘continuing my evaluation’ thought I’d better make a jump to another editor.

I haven’t used this to the extremes of TextPad, but it looks like its got all the right menu options. I’ve done some basic XML stuff with it, and it seems to be up to the task for my requirements at the moment.

Screenshot:

image

Notepad++

RescueTime

The most interesting tool this time round was RescueTime. I don’t think I’ve got an issue with wasting time, well at work at any rate, but thought I’d download and see exactly where my working day went.

The pleasing aspect was that it was able to work out programs that were linked to Software Development and Social Media etc…

The results are pretty good, indicating as thought I’m not wasting that much time, but I think there is room for improvement. I’ll certainly be using this tool in the New Year, and it could be a good basis for a blog post on our new team blog.

Screenshot:

image

Rescue Time

Android – Send Notification Code

The following code will send a notification, which will display in the status bar. Note that the Notification.FLAG_AUTO_CANCEL line (about line 8) will remove the notification when the user clicks it.


{

String ns = Context.NOTIFICATION_SERVICE;
 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
 int icon = R.drawable.icon;
 CharSequence tickerText = "Notification";
 long when = System.currentTimeMillis();
 Notification notification = new Notification(icon, tickerText, when);
 notification.flags = Notification.FLAG_AUTO_CANCEL;
 Context context = getApplicationContext();
 CharSequence contentTitle = "Notification";
 CharSequence contentText = notifications[getRandomNumber()];
 Intent notificationIntent = new Intent(this, MyTestApp.class);
 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
 notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

final int NOTIFY_ID = 1;
 mNotificationManager.notify(NOTIFY_ID, notification);
}

Android – Vibrate Code

Firstly, the Manifest file must include the permissions for VIBRATE:

<uses-permission android:name=”android.permission.VIBRATE”></uses-permission>

The actual code is:


Vibrator  myVibratorService = (Vibrator) getSystemService("vibrator");
 myVibratorService.vibrate(2000);

Note – to debug this I actually used this:


try {
 Vibrator  myVibratorService = (Vibrator) getSystemService("vibrator");

 if (myVibratorService != null) {
 myVibratorService.vibrate(2000);

 } else {
 Log.d("UHTestApp", "service == null");
 }
 }
 catch (Exception e) {
 String msg = "Exc: " + e.getMessage();

 //String msg = "Vibrate Selected";
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setMessage(msg)
 .setCancelable(false)
 .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int id) {
 dialog.cancel();
 }
 });
 AlertDialog alert = builder.create();
 alert.show();
 }

The first part encapsulates everything in a try…catch, which really does help when things don’t work as expected. The catch is just a way of getting amessage box to pop-up with details.

Android Development – Getting Started

Recently I’ve been traveling by train a lot, and the National Rail website provides an outstanding service of being able to display train information for journeys from a specified station to another station. A downside though is that the page to specify the journey options is incredibly slow to render on a mobile phone.

I decided I’d write a little Android App to take the information from myself and then redirect to render their results webpage in the browser. The ideal solution for this would have been just a webpage, however I’m not sure about wanting to open this up to everybody, and besides it was a good learning opportunity.

Installation of Tools

Firstly, I did this on a works PC, so was running Windows XP. I installed ‘Eclipse IDE for Java Developers (Vn 3.5 SR 2) from http://www.eclipse.org/download. Once the download had been extracted I start Eclipse to make sure everything appeared to be functioning.

Next was to download the Android SDK (http://developer.android.com/sdk/index.html) and I extracted this to C:\AndroidSDK\

I then needed to update the Windows Environment PATH setting to include the SDK location. This was achieved by right-clicking My Computer-Properties-System Environment and finding the path setting.

Next was to add the Android Development Tools. In Eclipse, select the Help menu and then the Add New Software option. Enter the path https://dl-ssl.google.com/android/eclipse

Click next, accept all licences, next and then restart the IDE when prompted to. Then head to the Windows menu and select Preferences. Set the directory to the SDK directory.

Finally go to Windows menu, select Android SDK and AVD Manager, click all the check boxes and accept all licenses and install.

Confirming Installation

Select the File menu and create a new Android project.

Right click on the project and select Run As Android Application. You’ll be prompted to create a new application. Once created, refresh the device selection screen and the new device will be displayed. Select the device and after a short delay (depending on the spec of the machine) the Android emulator should appear with a Hello World test app.

In my next post I’ll go through the details of creating the actual application.