Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions problems/skiing-in-singapore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Skiing in Singapore
I came across this programming excercise from redmart that caught my interest. At the same time im in the midst of the harvard's cs50 course which i took through edx as a refresher. So I thought of taking up the programming excercise challenge and try to implement it using c. So without further ado, the challenge description goes like this:

====================

Sometimes it's nice to take a break and code up a solution to a small, fun problem. Here is one some of our engineers enjoyed recently called Skiing In Singapore.

Well you can’t really ski in Singapore. But let’s say you hopped on a flight to the Niseko ski resort in Japan. Being a software engineer you can’t help but value efficiency, so naturally you want to ski as long as possible and as fast as possible without having to ride back up on the ski lift. So you take a look at the map of the mountain and try to find the longest ski run down.

In digital form the map looks like the number grid below.

4 4
4 8 7 3
2 5 9 3
6 3 2 5
4 4 1 6

The first line (4 4) indicates that this is a 4x4 map. Each number represents the elevation of that area of the mountain. From each area (i.e. box) in the grid you can go north, south, east, west - but only if the elevation of the area you are going into is less than the one you are in. I.e. you can only ski downhill. You can start anywhere on the map and you are looking for a starting point with the longest possible path down as measured by the number of boxes you visit. And if there
are several paths down of the same length, you want to take the one with the steepest vertical drop, i.e. the largest difference between your starting elevation and your ending elevation.

On this particular map the longest path down is of length=5 and it’s highlighted in bold below: 9-5-3-2-1.

4 4
4 8 7 3
2 5 9 3
6 3 2 5
4 4 1 6

There is another path that is also length five: 8-5-3-2-1. However the tie is broken by the first path being steeper, dropping from 9 to 1, a drop of 8, rather than just 8 to 1, a drop of 7.

Your challenge is to write a program in your favorite programming language to find the longest (and then steepest) path on this map specified in the format above. It’s 1000x1000 in size, and all the numbers on it are between 0 and 1500.

Send your code or a github link (and a resume if you like) to [?????? at redmart dot com], replacing “??????” with the concatenation of the length of the longest path with the largest drop, and the size of the drop. So in the simple example above length=5, drop=8, so the email address would be [58 at redmart dot com]. If your e-mail gets through - you got the right answer.

Good luck and have fun!
262 changes: 262 additions & 0 deletions solutions/c/sgski.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
// required; otherwise clang will complain that getline has not been declared
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
int **matrix;
int rowCount;
int colCount;
} matrix;

typedef struct {
char* solution;
int distance;
int drop;
} solution;

typedef struct {
int row;
int col;
} cellIndex;

// input file reading routines
void readfile(matrix *m, FILE* fp);
void initMatrix(matrix *m, char* line);
void readline(matrix *m, char* line, int rowIndex);

// solution finder
void findSkiPath(matrix *m, solution *sol);
void checkAdjacentCells(const char* path, matrix *m, cellIndex index, solution *sol, int currentValue);
void evaluateSolution(solution *sol, const char* path);

// miscellaneous routines
void showContents(matrix *m);

int main(int argc, char* argv[]) {

if(argc != 2) {
printf("usage: sgski <input file>\n");
exit(1);
}

char* filename = argv[1];
FILE *ifp = fopen(filename, "r");
if (ifp == NULL) {
printf("Unable to open input file %s\n", filename);
exit(EXIT_FAILURE);
}

// initialize the solution structure
solution *sol = malloc(sizeof(solution));
sol->solution = malloc(sizeof(char) * 100);
sol->distance = 0;
sol->drop = 0;

matrix *m = malloc(sizeof(matrix));

// read the input file into the matrix
readfile(m, ifp);

// close file after reading
fclose(ifp);

findSkiPath(m, sol);

printf("Ski Path: %s; Distance: %d; Drop: %d\n", sol->solution, sol->distance, sol->drop);

// release resources
free(sol);
free(m);

return 0;
}

void findSkiPath(matrix *m, solution *sol) {
for (int i = 0; i < m->rowCount; i++) {
for (int j = 0; j < m->colCount; j++) {
int value = m->matrix[i][j];
char* path = malloc(sizeof(char) * 6);
sprintf(path, "%d ", value);

cellIndex index;

// check east
index.row = i;
index.col = j + 1;
checkAdjacentCells(path, m, index, sol, value);

// check west
index.row = i;
index.col = j - 1;
checkAdjacentCells(path, m, index, sol, value);

// check north
index.row = i - 1;
index.col = j;
checkAdjacentCells(path, m, index, sol, value);

// check south
index.row = i + 1;
index.col = j;
checkAdjacentCells(path, m, index, sol, value);
}
}
}

void checkAdjacentCells(const char* path, matrix *m, cellIndex index, solution *sol, int currentValue) {

// The base case - If we go beyond the limits of the matrix
if(index.row < 0 || index.row > (m->rowCount - 1)
|| index.col < 0 || index.col > (m->colCount - 1)) {
evaluateSolution(sol, path);
return;
}

// check if the next cell has a lower value than the current cell
int val = m->matrix[index.row][index.col];
if(val < currentValue) {
char* newPath = malloc(sizeof(char) * (strlen(path) + 4 + 1 + 1)); // the 4-digit value + space + \0
strcpy(newPath, path);

char *ch = malloc(sizeof(char) * (5 + 1)); // support upto 4-digit value and \0 (string terminator)
if(ch == NULL) {
printf("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
sprintf(ch, "%d ", val);
strcat(newPath, ch);
free(ch);

int r = index.row, c = index.col;

// check east
index.row = r;
index.col = c + 1;
checkAdjacentCells((const char*) newPath, m, index, sol, val);

// check west
index.row = r;
index.col = c - 1;
checkAdjacentCells((const char*) newPath, m, index, sol, val);

// check north
index.row = r - 1;
index.col = c;
checkAdjacentCells((const char*) newPath, m, index, sol, val);

// check south
index.row = r + 1;
index.col = c;
checkAdjacentCells((const char*) newPath, m, index, sol, val);

free(newPath);
}

// all ajacent cells have bigger value then the current cell
evaluateSolution(sol, path);
return;
}

/**
* Checks if the longest path with the steepest drop has been found.
*/
void evaluateSolution(solution *sol, const char* path) {
// split the string by the space delimiter
int distance = 1;
char *dropTemp[2];
dropTemp[0] = strtok(strdup(path), " ");
char* end = dropTemp[1] = strdup(dropTemp[0]);

while ((end = strtok(NULL, " ")) != NULL) {
dropTemp[1] = end;
distance++;
}

if(distance < sol->distance) {
return;
}

int drop = atoi(dropTemp[0]) - atoi(dropTemp[1]);
if(distance > sol->distance || drop > sol->drop) {
strcpy(sol->solution, path);
sol->distance = distance;
sol->drop = drop;
}
}

void readfile(matrix *m, FILE* fp) {
int rowIndex = 0;
size_t len = 0;
size_t read = -1;
char *line;

while ((read = getline(&line, &len, fp) != -1)) {
if (rowIndex == 0) {
// the first row of the input file
// contains the size of the matrix.
initMatrix(m, line);
} else {
readline(m, line, rowIndex);
}

rowIndex++;
}
}

/**
* Reads the size of the matrix from the first line of the input file and
* sets the row and column counts into the parameters rowCount and colCount
* attributes of matrix m.
*
* This function is to be called on the first line of the input file.
*/
void initMatrix(matrix *m, char* line) {

// reads the row count - the first value on the line string
char *ch = strtok(line, " ");
m->rowCount = atoi(ch);

// reads the column count - the second value on the line string
ch = strtok(NULL, " ");
m->colCount = atoi(ch);

// initialize a two-dimentional array of size rowCount * columnCount
int** matrix = (int **) malloc(sizeof(int *) * m->rowCount);
for(int i = 0; i < m->rowCount; i++) {
matrix[i] = (int *) malloc(sizeof(int) * m->colCount);
}

m->matrix = matrix;
}

void readline(matrix *m, char* line, int rowIndex) {
int colIndex = 0;
char *ch = strtok(line, " ");

while(ch != NULL) {
int val = atoi(ch);
if(val > 9999) {
printf("Invalid input file. Cannot have value greater than 9999\n");
exit(EXIT_FAILURE);
}

m->matrix[rowIndex - 1][colIndex] = atoi(ch);
ch = strtok(NULL, " ");
colIndex++;
}
}

/**
* Prints the contents of the matrix into the console
*/
void showContents(matrix *m) {
for(int i = 0; i < m->rowCount; i++) {
for (int j = 0; j < m->colCount; j++) {
printf("%d ", m->matrix[i][j]);
}
printf("\n");
}
}