Duncan's blog

September 23, 2014

Project Euler: problem 5 (PHP)

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 5:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

Code:

<?php
$step = 20;
$factor = $step - 1;
$i = $step;

while (true) {
	if ($i % $factor == 0) {
		if ($factor == 11) {
			break;
		}
		
		$factor--;
		
		$step = $i;
	} else {
		$i += $step;
	}
}

echo $i;


So a simple while loop that I break out of once we get down to 11.

September 22, 2014

Project Euler: problem 4 (PHP)

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 4:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Nice and easy:

<?php
$palindrome = 0;

for ($i = 100; $i <= 999; $i++) {
	for ($j = 100; $j <= 999; $j++) {
		$x = $i * $j;
		if ($x > $palindrome && $x == strrev($x)) {
			$palindrome = $x;
		}
	}
}

echo $palindrome;


strrev() being the PHP equivalent of ColdFusion’s more obviously-named reverse().

September 21, 2014

Project Euler: problem 3 (PHP)

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Ok, now we’re starting to get into some more interesting code. I’m merely trying to convert my previous CFML approach into PHP, and assuming the basic logic is correct. There’s probably much better ways to do this though.  I did simplify my code somewhat this time, previously I was using recursion to calculate all the factors.  It’s still not ideal (I’m aware of an obvious flaw in it), but it returns me the correct answer.

<?php
$limit = 600851475143;
$primes  = array();

function isPrime($x)
{
	if ($x < 2)
	{
		return false;
	}
	
	if (($x % 2 == 0) && ($x > 2))
	{	// a multiple of 2, but not 2 itself
		return false;
	}
	
	for ($i = 3; $i <= sqrt($x); $i += 2)
	{
		if ($x % $i == 0)
		{	// found a factor of x
			return false;
		}
	}
	
	return true;
}

function findPrimes($x)
{
	// need to re-declare $primes as a global variable so this function can access it:
	global $primes;
	
	for ($i = 3; $i < sqrt($x); $i += 2)
	{
		if ((fmod($x,$i) == 0) && isPrime($i))
		{
			if (! in_array($i, $primes))
			{
				array_push($primes, $i);
			}
		}
	}
}

findPrimes($limit);
rsort($primes,  SORT_NUMERIC);
echo $primes[0];

So some things worth mentioning.

1. In order to access the variable $primes inside the findPrimes function, I had to re-declare it as ‘global’ within that function. I should just have rewritten the function to simply return an array.

2. I couldn’t simply do $x % $i == 0 to calculate the modulus, this didn’t seem to work due to the size of the values. I didn’t bother spending any time to investigate at what point this stopped working, what size of integers PHP couldn’t happily handle, or what was the exact problem. Instead I just used the fmod() function, which seemed fine.

3. Rather than just dump out the entire array, I used rsort() to sort it numerically in descending order, then output the first element in the array.  There’s better ways obviously of getting the last element in an array.

4. I’m using the array functions in_array($value, $array) and array_push($array, $value) – notice already the inconsistency in the order of the arguments, something I’ve seen mentioned in a few places.  These are the PHP equivalents of CFML’s ArrayFind(array, value) and ArrayAppend(array, value)

September 20, 2014

Project Euler: problem 2 (PHP)

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Project 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.

A minor clarification in the specification from when I did this last.

<?php
$sum = 0;
$fibonacci = 1;
$old1 = 0;
$old2 = 1;

while ($fibonacci <= 4000000) {
	$fibonacci = $old1 + $old2;
	$old1 = $old2;
	$old2 = $fibonacci;
	
	if ($fibonacci % 2 == 0) {
		// it's an even number
		$sum += $fibonacci;
	}
}

echo $sum;

Be sure and read my friend and colleague Adam Cameron’s blog article about another way to do the Fibonacci sequence in PHP using generators.

September 19, 2014

Project Euler: problem 1 (PHP)

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

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.

So not too tricky to start with:

<?php 
$sum = 0;

for ($i = 1; $i < 1000; $i++) {
	if ($i % 3 == 0 || $i % 5 == 0) {
		$sum += $i;
	}
}

echo $sum;
?>

The only thing I really noticed was that I could have used fmod(x, y) instead of x % y == 0 to calculate the modulus values, although I didn’t see any benefit in doing so at this point, with such small integers.  However it wasn’t long before I had to do so (in the third Project Euler puzzle).

Project Euler redux

Filed under: PHP,Project Euler — duncan @ 8:00 am
Tags: ,

A few years ago I did several of the Project Euler puzzles, a series of mathematical problems that are good programming exercises.  I started out doing them in ColdFusion, but ended up doing a a few in Python due to its better abilities at dealing with massive numbers and calculations.

I’ve now decided to convert at least some of them from CFML / Python code into PHP, as a little tutorial for myself to increase my familiarity with some of its basic syntax.  I’m doing this for basically the same reasons my colleague Adam Cameron is shifting his blog’s focus from ColdFusion to PHP.

I’m not going to try and solve the problems that I’ve already done by looking at them completely from scratch.  Instead I’ll assume my logic or approach from before was basically sound, and try to simply convert the code into PHP, perhaps with minor improvements.

What I’m  hoping is I’ll get used to common PHP functions and perhaps some gotchas that a newcomer to the language wouldn’t automatically be aware of.  If you happen to be reading any of these, have some experience in the language and spot anything daft I’m doing or know better approaches and so on, I’d appreciate any feedback.

So without further ado, here’s the first Project Euler puzzle, a load more will hopefully follow.

August 9, 2014

Google Maps API – draggable polygons

Filed under: Google Maps,Javascript — duncan @ 8:00 am
Tags: , , , ,

This post was in response to a question on StackOverflow, asking how to make a draggable and editable polygon, but restrict it to always be a pentagon.

Firstly, it’s quite simple to allow a user to drag the points on a polygon, just add ‘editable: true’ to the PolygonOptions.  However it’s not possible to restrict the number of points it has; by default Google places draggable spots on the mid-points of each edge; if the user drags these then it adds an additional point.

<script>
    function initialize() {
        var map = new google.maps.Map(document.getElementById("map_canvas"), {
            zoom: 15,
            center: {lat: 51.476706, lng: 0},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        
        // create an array of coordinates for a pentagonal polygon
        var arrCoords = [
            new google.maps.LatLng(51.474821, -0.001935),
            new google.maps.LatLng(51.474647, 0.003966),
            new google.maps.LatLng(51.477708, 0.004073),
            new google.maps.LatLng(51.479753, 0.000468),
            new google.maps.LatLng(51.477654, -0.002192)
        ];
        
        var polygon = new google.maps.Polygon({
            editable: true,
            paths: arrCoords,
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map: map
        });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

This then gives us a pentagon like:

polygon1

If we start to drag any of those points in the centre of an edge, we can ultimately end up with something like this, very far from being a pentagon:

polygon2

So, how to get around this?  My idea is that instead of making the polygon editable, we simply add our own markers to each of the 5 vertices.  These are draggable, and in response to the user dragging them, we update the polygon path.

<script>
    function initialize() {
        var map = new google.maps.Map(document.getElementById("map_canvas"), {
            zoom: 15,
            center: {lat: 51.476706, lng: 0},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        
        // create an array of coordinates for a pentagonal polygon
        var arrCoords = [
            new google.maps.LatLng(51.474821, -0.001935),
            new google.maps.LatLng(51.474647, 0.003966),
            new google.maps.LatLng(51.477708, 0.004073),
            new google.maps.LatLng(51.479753, 0.000468),
            new google.maps.LatLng(51.477654, -0.002192)
        ];
        
        var polygon = new google.maps.Polygon({
            paths: arrCoords,
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map: map
        });
        
        // add a marker at each coordinate
        for (var i = 0; i < arrCoords.length; i++) {
             var marker = new google.maps.Marker({
                position: arrCoords[i],
                map: map,
                draggable: true
            });
                        
            bindMarker(marker, arrCoords, i, polygon);
        }
    }
    
    function bindMarker(marker, arrCoords, i, polygon) {
        google.maps.event.addListener(marker, 'dragend', function(e) {
             arrCoords[i] = e.latLng;
             polygon.setPath(arrCoords);
        });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

When a marker gets dragged, we update the coordinates of the corresponding point in our path array.  We then update the path on the polygon.  Simple!

polygon3

After dragging the markers, we still have only 5 edges:

polygon4

So that’s all very well and good, but those markers can be a bit obtrusive looking on our page.  Well we can specify custom icons instead.  In this case we can even just use the Symbol class to come up with something much nicer looking:

            var marker = new google.maps.Marker({
                position: arrCoords[i],
                map: map,
                draggable: true,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 5,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#FFFFFF",
                    fillOpacity: 1
                }
            });

polygon5

Also it might be that we want to be able to drag the entire polygon to another location on the map (and was a requirement of the original question on StackOverflow).  In that case we have to update the markers at the same time.  It gets slightly more complicated here; basically I create an array of markers (always useful anyway).  Each time we drag the polygon, we update this array.  We also remove any markers previously created.

<script>
    function initialize() {
        var map = new google.maps.Map(document.getElementById("map_canvas"), {
            zoom: 15,
            center: {lat: 51.476706, lng: 0},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        
        // create an array of coordinates for a pentagonal polygon
        var arrCoords = [
            new google.maps.LatLng(51.474821, -0.001935),
            new google.maps.LatLng(51.474647, 0.003966),
            new google.maps.LatLng(51.477708, 0.004073),
            new google.maps.LatLng(51.479753, 0.000468),
            new google.maps.LatLng(51.477654, -0.002192)
        ];
        
        var polygon = new google.maps.Polygon({
            paths: arrCoords,
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map: map,
            draggable: true
        });
        
        var markers = addMarkers(arrCoords, map, polygon, []);
        
        google.maps.event.addListener(polygon, 'dragend', function(e) {
             markers = addMarkers(this.getPath().getArray(), map, this, markers);
        });
    }
    
    function addMarkers(arrCoords, map, polygon, oldMarkers) {
        var markers = [];
        
        // clear any existing markers
        for (var i = 0; i < oldMarkers.length; i++) {
            oldMarkers[i].setMap(null);
        }
        
        // add a marker at each coordinate
        for (var i = 0; i < arrCoords.length; i++) {
             var marker = new google.maps.Marker({
                position: arrCoords[i],
                map: map,
                draggable: true,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 5,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#FFFFFF",
                    fillOpacity: 1
                }
            });
        
            bindMarker(marker, arrCoords, i, polygon);
            
            markers.push(marker);
        }
        
        return markers;
    }
    
    function bindMarker(marker, arrCoords, i, polygon) {
        google.maps.event.addListener(marker, 'dragend', function(e) {
             arrCoords[i] = e.latLng;
             polygon.setPath(arrCoords);
        });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

July 1, 2014

20 funny pub signs

Filed under: Funny — duncan @ 8:00 am
Tags: ,

More amusing, witty and clever A-board signs, this time all booze-inspired!

There's a beer garden & beerAlcohol may not solve your problems but neither will waterOur beer is as cold as your ex girlfriend's heartKeep it secret we have a huge beer gardenBeware of strong drink... it will make you shoot at tax collectors... and missRevenge is a dish best served cold. In fact scrub that, I meant beerCure your hangover with burgers and more boozeIf the answer's not beer... you're asking the wrong questions!Beer isn't the answer. It's the question. The answer is yes!Girls don't make passes at guys with pint glassesNever cry over spilt milk. Spilt cocktails are far more tragic!Due to very hot temperatures... it's advised that you hydrate at least 5 times a dayWine improves with age, the older I get, the better I like itI distrust camels & anyone else who can go a week without a drink!It's a smile, it's a kiss, it's a sip of wine, it's summertimeThe recession is over! Buy beer & houses!Dear Pope, come in for a swift one!Rudolph the red nosed reindeer... probably over indulged on the sherry we all leave outBook with us for your xmas lunches, parties or just a p*** upFREE BEER

Thanks to the following, and all those I can’t remember where they were:

June 25, 2014

25 funny coffee shop signs

Filed under: Coffee,Funny — duncan @ 8:00 am
Tags: , , ,

A day without coffee is like something without something

1. Fleet Street Press mastering the art of a good simile.

 

life is a beautiful and endless journey in search of the perfect cup!

2. Knockbox Coffee getting all zen.

 

free coffee for anyone doing the umbrella dance!

3. Department of Coffee and Social Affairs wondering if you feel like dancing.

 

Coffee - a warm, delicious alternative to hating everybody every morning forever!!!

4. Fleet Street Press

 

I'd rather take coffee than compliments just now!

5. Knockbox Coffee

 

Coffee is the foundation of my food pyramid

6. Fleet Street Press

 

But first, coffee

7.  Vittles Coffee, Edinburgh

 

trams: £1079.48 per Edinburgh resident, espresso: £2

8. Artisan Roast‘s coffee offering value for money for Edinburgh residents compared to the trams.

 

Coffee solves everything

9. Artisan Coffee, Stamford Brook

 

Sleep is a symptom of caffeine deprivation

10. Fleet Street Press

 

Free coffee!

11.  Fork Deli

 

Coffee, one meal to rule them all!

12. Beany Green

 

your name

13. Department of Coffee and Social Affairs

 

coffee makes the afternoon better & quicker

14. Department of Coffee and Social Affairs

 

secret ingredient to the Egyptian revolution?

15. Notes providing the solution to the Egyptian revolution.

 

spring is here! - but we still need coffee!

16. Fleet River Bakery

 

wake up sleeping beauty

17. Fleet River Bakery

 

♥

18. Artisan Roast

 

probably the best coffee in Tollcross and definitely the best tea

19. Modesty isn’t the best policy for Pekoe Tea.

 

coffee for passion

20.  The Borough Barista

 

creative fuel

21. Department of Coffee and Social Affairs

 

tube strikes suck!!!  our coffee doesn't!!!

22. Fleet River Bakery

 

coffee never goes on strike

23. Fleet Street Press

 

coffee

24. Quiet understatement from Brick Lane Coffee.

 

you've gotta fight for your right to latte

25. Four Corners Cafe

May 20, 2014

12 more funny A-boards

Filed under: Funny — duncan @ 6:37 pm
Tags:

A random selection of some more unusual / funny signs outside pubs, coffee shops and cafés.

Beer me up ScottyYour mum ate my Meat PornHipster or Santa?Nobody's ugly after three drinks here!Name the whiskey: _U__EIT __UR__NCarbon Monoxide is a myth. The air contains prunes and only prunesPrivate sign. Do not readHe was a wise man who invented beer - PlatoPut on your pants! It's time for coffeee!Caffeine to get you to ChristmasIn three words I can sum up what I've learned about life: it goes onLife is short. Eat dessert first!

Credit to:

Next Page »

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 534 other followers