# code challenge

Go to solution Solved by Barand,

## Recommended Posts

Hi guys and girls,

A recruiter asked me to do this coding challenge and was wondering if you had a more elegant solution or your thoughts on it.

EXERCISE FOR DEVELOPER CANDIDATES: Unit Number Sorting Exercise

We often deal with unit number / resident name data. These two pieces of information are used by our users to identify a lease. Many of our screens and reports show a list of leases.

The task is to sort lease data read from a file and to print the sorted data to STDOUT. The data looks as follows (sample also attached):

#50 - Smith

#8 - Johnson

#100 - Sanders

#1A - Kessenich

Each line contains a unit number and a resident name. The data should be sorted by unit number.

Develop a solution in PHP and one other language of your choice that reads the data from a file and prints the data (sorted by unit number) to STDOUT. The printed strings should not be modified from how they appear in the input file.

Here is my solution:

<?php
define('br','<br />');

// open the file
\$fp = fopen('input.txt','rb+');

if (false === \$fp)
{
die ('failed to open file');
}

\$numbers = array();
\$letters = array();

// read the file line by line
while ((\$line = fgets(\$fp, 1024)) !== false)
{
// split the string by unit number and name
\$str = explode(' - ',\$line);

// separate unit numbers from units with letters
if (preg_match('/[a-zA-Z]/', \$str[0]))
{
\$letters[\$str[0]] = \$str[1];
}
else
{
\$numbers[\$str[0]] = \$str[1];
}
}

if ( ! feof(\$fp))
{
}

fclose(\$fp);

// sort each array
ksort(\$numbers,SORT_STRING);
ksort(\$letters,SORT_STRING);

// merge arrays with unit letters appearing first
\$output = array_merge(\$letters, \$numbers);

// output data
foreach (\$output as \$key => \$value)
{
echo \$key . ' - ' . \$value . br;
}

##### Share on other sites

A simpler solution would be to read the file content into an array using file, sort the data using usort and then print it using a simple loop.

The compare function for usort would handle extracting the unit number from the strings and compare them to sort the data.

##### Share on other sites

• Solution

or

\$data = file('hansford.txt',FILE_IGNORE_NEW_LINES);
natsort(\$data);
foreach (\$data as \$line) {
echo "\$line<br>";
}

gives

#1A - Kessenich
#8 - Johnson
#50 - Smith
#100 - Sanders
##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
×
• Create New...