## Friday, September 2, 2011

### The Led Clock Problem

This morning I had some free time and I made The Clock of the Tuenti Programming Contest.

In this problem we have a digital (7 led segment) clock and we have to count how many times will the individual leds turn on after X seconds (starting form 00:00:00 position).

We have to take into account that every second all leds turn off and then the ones of the next position will turn on.

Sample Input:
```0
4
```

Sample output:
```36
172
```

I made a quite simple solution for Java:
1. We parse the input.
2. For each second we calculate the value that each led will have.
3. We calculate the number of leds on for each of the previous led value and add all of them.
4. We print the final result.

This solution has a complexity in big O notation of O(6*N) being N the input number of seconds.

The code is shown below:
```/**
* problem http://contest.tuenti.net/Question_6.html
* @author gru
*/
public class Main {

//these constants contain the number of leds on for each number
static final int zero = 6;
static final int one = 2;
static final int two = 5;
static final int three = 5;
static final int four = 4;
static final int five = 5;
static final int six = 6;
static final int seven = 3;
static final int eight = 7;
static final int nine = 6;

public static void main(String[] args) {

//parse the input (time in seconds)
int input = Integer.parseInt(args[0]);

//count will contain the output
int count = 0;

//each iteration calculates one second
for (int i = 0; i <= input; i++)
count += toTime(i);

//print out the result
System.out.println(count);
}

//this method converts seconds to a real hour
private static int toTime(int i) {
int count = 0;

//hours units
count += toLeds((i / 6000) % 10);
//hours tens
count += toLeds(((i / 6000) % 100) / 10);

//minutes units
count += toLeds((i / 60) % 10);
//minutes tens
count += toLeds(((i / 60) % 100) / 10);

//seconds units
count += toLeds((i % 60) % 10);
//seconds tens
count += toLeds(((i % 60) % 100) / 10);

return count;
}

//this method returns the # of leds turned on for each digit (0-9)
private static int toLeds(int i) {

if (i == 0)
return zero;
else if (i == 1)
return one;
else if (i == 2)
return two;
else if (i == 3)
return three;
else if (i == 4)
return four;
else if (i == 5)
return five;
else if (i == 6)
return six;
else if (i == 7)
return seven;
else if (i == 8)
return eight;
else
return nine;
}
}
```