Code snippets

When I write a code snippet or a short program, I post the source code here for all to see. Browse through all the code below, or choose a language.

Project Euler 4: Largest Palindromic Number with 6 Figures

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

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

There is probably an elegant way of doing this, but I prefer the easier method of brute force. This is a Perl script that calculates every product of three-digit numbers and saves all of the palindromic numbers in a list. It then sorts the list in descending numerical order and prints the first element in the list.

1
2
3
4
5
6
7
8
9
10
my @l; # the list for all the palindrom numbers
for ( my $n = 999; $n > 99; $n-- ) { # do for 100 to 999
	for ( my $m = $n; $m > 99; $m-- ) { # do for 100 to $n
		if ( $n*$m == reverse( $n*$m ) ) { # if the product is a palindrom..
			push @l, $n*$m; # ..add it to the list
		}
	}
}
@l = sort { $b <=> $a } @l; # sort @l numerically with the largest number first
print $l[0]; # print the first element (the largest number)

The script finishes in about a second. Note line 3, the second for loop. Since $n times the numbers higher than $n have already been multiplied earlier in the loop, these can be left out to save time.

Project Euler 3: Find the Largest Prime Factor

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 317584931803?

To calculate the prime factors, I loop through the prime numbers, dividing the number with each if it is divisible. I used a modified version of my prime calculator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
my $m = 3175849318035832905;
my @primes = ();
my $i = 1, $b = 0;
while ( $i < $m ) { # looped until the final prime factor has been found
	$i++;
	foreach (@primes) {
		if( ! ( $i % $_ ) ) {
			$b = 1;
			next;
		}
	}
	if ( $b ) {
		$b = 0;
	} else { # if it is a prime
		push @primes, $i;
		while ( ! ( $m % $i ) ) { # as long as $m is divisbible by the prime
			print "$i \n"; # print the prime (since it's a prime factor)
			$m /= $i; # divide $m by the prime
		}
	}
}

The last number printed is the highest prime factor. Explanations for the modifications are in the code.

Sort a string internally with Perl

The following code sorts a given string internally in order of the characters’ ASCII values.

print sort split '', <STDIN>

A per-line analysis of the code wouldn’t say very much. This is the code with brackets added:

print( sort( split( '', <STDIN>) ) )

First, the input (<STDIN>) is split into an array with split. The first argument, '', means that it splits every character. sort sorts it in ASCII order, and the result is finally printed. The only flaw is that the linebreak (ASCII 10) is put first, and so you see a double linebreak between the input and the output.

List of bbPress Template Functions

In order to ease template writing for bbPress, i compiled a list of all the template functions in the current version (bbPress 0.8.1). It was done swiftly with grep -oe ^function.*\) bb-includes/template-functions.php | sort > functions.txt.

(more…)

BounceFuck: Simple Subtraction

This code is the code for simple addition with a few minor changes. It can subtract any two numbers between 0 and 9 as long as the difference is between 0 and 9.

1
2
3
4
5
6
7
8
/ !|-!\}-v{.
\{\/\/\ {/
/ -----\
,/-----/
}\-- --\
,/-----/
$\-----\
\/\/\/\/

Note that the start has been rearranged from the addition-script. This is because the second input must be subtracted by 48 and not the first, since subtraction, as opposed to addition, is not symmetrical.

BounceFuck: Effective, Simple Addition

Looks like my previous attempt at an addition-only calculator in BounceFuck was very ineffective. This script does the same thing, but in about 1/3 of the space.

1
2
3
4
5
6
7
8
/,!|+!\{-v}.
\}\/\/\ }/
$,-----\
 /-----/
 \-- --\
 /-----/
 \-----\
  \/\/\/

The difference is that here, 48 is subtracted only once. The other addition-calculator subtracted 48 from two memory cells and added it to one.

BounceFuck: Simple Addition

The following BounceFuck code makes a very simple addition-only calculator. It can add numbers between 0 and 9 as long as the sum is less than 10. The two numbers are taken as arguments.

1
2
3
4
5
6
7
8
9
10
/+|+!,O!O!}+|
}/+{  \O/\/\/\/\
+}O$,!+-----\+++\
!\/ --/-----/+++/
O! /}}\-----\+++\
+\<-/+/-----/+++/
+/\ {\\-----\+++\
+++^\{ \/\/\/+++/
++\+O\!\! |\/\/ 
\/   Q    /.+++/

The first part takes the two arguments and subtracts 48 (the ASCII number for 0) from both of them. This leaves us with their numerical values in the first and second cells. After this, two loops transfer first the second cell and then the first cell to the third cell. 48 is added again to the third cell, and the result is printed.

Put bbPress in Maintenance Mode

If you want to test a new plugin or theme in bbPress, you might want to disable the site for regular users. Add the following code to the end of bb-settings.php:

1
2
3
if ( ! bb_current_user_can( 'administrate' ) ) {
  die( '<p>The site is down for maintenance.</p>' );
}

This modification will only show pages for users who have the “administrate” capability. Make sure that you log in before you upload the new bb-settings.php.

Simple Snake Game in TI Basic

This is a very simple Snake game written in TI Basic. The snake starts in the middle of the display and grows very quickly, i.e. its end stays in the same position. You can add obstacles by setting graphs, since they are drawn before the game starts. If you reach three consecutive pixels, you lose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
: Pxl-On( 1, 1 )
: ClrDraw
: 46 -> X
: 32 -> Y
: While 1
: getKey -> K
: If ( K > 23 and K < 27 ) or K = 34 : K-> D
: If D = 24 : X - 1 -> X
: If D = 25 : Y - 1 -> Y
: If D = 26 : X + 1 -> X
: If D = 34 : Y + 1 -> Y
: If pxl-Test( Y, X ) : Then : A + 1 -> A : If A > 2 : Stop : Else : 0 -> A : End
: Pxl-On( Y, X )
: End

Time for explanation, then:

  • Line 1 puts a pixel on the display in order to bring the graphical window up. If this is not done, line 2 has no effect.
  • Line 2 clears the graph window of any prior snakes.
  • Lines 3-4 sets the initial coordinates of the snake’s head in the center of the display. The display is 92 pixels wide and 64 pixels high.
  • Line 5 starts the game loop.
  • Line 6 gets the key input and stores it into K. This is done so that the same key can be used in the next statement.
  • Line 7 checks whether K is one of the direction keys. If it is, it is stored into the direction variable.
  • Lines 8-11 check what the direction variable is set to, and adjusts the snake’s head accordingly.
  • Line 12 is a nested If statement. It can be rewritten as follows in pseudo-code:
    If ( pxl-Test( Y, X ) ) {
        A + 1 -> A
        If ( A > 2 ) {
            Stop
        }
    } Else {
        0 -> A
    }

    If the snake’s head is on a pixel, the consecutive pixel count — A — is incremented. Then, if A is greater than 2, i.e. this was the third pixel, the game loop (and thereby the game) ends. If it was not a pixel, the pixel count is reset to 0.

  • Line 14 marks the end of the game loop. Here, it starts over at line 5 again.

Calculating Pi in TI Basic Using the Leibniz Formula

Got nothing to do during math class? Then let your calculator calculate Pi! The Leibniz formula states that:

Pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 …

This is how to do it on your TI calculator, nicely formated.

: 0 -> N
: 0 -> P
: ClrHome
: Output( 1, 1, "STEP " )
: Output( 2, 3, "PI= " )
: While 1
: 1 / ( (-1)^N(2N+1) ) + P -> P
: Output( 1, 6, N )
: Output( 2, 6, 4P )
: N + 1 -> N
: End

Note that this is a very poor way of calculating Pi, especially with a calculator, since it requires an extremely large amount of steps in order to obtain accurate values. 10,000,000,000 operations are required in order to get only ten correct decimals.

« Later PostsEarlier Posts »
FireStats iconAnvänder FireStats