[chbot] New chocolate fish challenge
Stephen Irons
stephen.irons at clear.net.nz
Wed Nov 19 20:20:27 GMT 2014
>
> At 03:36 p.m. 19/11/2014, you wrote:
>
>> I'm building a jumbo LED clock (using 8" 7-segment displays) for the local pool, as I can't read a small analogue clock without my glasses when swimming. The PCBs are on their way from China as I type....
>>
>> So here is the challenge. Make a C function that usually returns 0, but returns a value of 1 once in every 60 calls calls - just like this:
>>
>> int chocolate_fish(void)
>>
>> {
>>
>> unsigned counter = 0;
>>
>> if(counter == 59) {
>>
>> counter = 0;
>>
>> return 1;
>>
>> }
>>
>> counter++;
>>
>> return 0;
>>
>> }
>>
>> Now to make it hard. You can't use any math operations - no addition, subtraction multiplication or division, including the increment/decrement operations.
>>
>> Bonus points for using no more static memory than one byte, and code less than 10 lines - with each statement on a line of their own.
>>
>> Mike
>>
(I lost the original message, so have replied to an early response)
I would contend that a comparison is an arithmetic operation: most
CPUs subtract and compare with zero.
My version assumes that flash (or ROM) is cheap, and RAM is expensive.
It has a constant array containing the next count value and output
value. It hides the arithmetic operation in an array de-reference.
-------- 8< --------
#include <stdint.h>
#include <stdio.h>
typedef struct
{
uint8_t count;
uint8_t output;
} state_t;
const state_t states[] =
{
{ 1, 0 },
{ 2, 0 },
{ 3, 0 },
{ 4, 0 },
{ 5, 0 },
{ 6, 0 },
{ 0, 1 },
};
state_t counter(void)
{
static int count;
state_t next_state = states[count];
count = next_state.count;
return next_state;
}
int main(int argc, char * argv[])
{
int i = 0;
state_t state;
while (1)
{
i += 1;
state = counter();
printf("%d %d %d\n", i, state.count, state.output);
}
}
-------- 8< --------
The actual counter function is less than 10 lines. The array
definition *could* be one long line; it is one statement. I'm not sure
about the typedef.
The typedef could pack both the next count value and the output into
one byte, and count up to 127.
Please explain why all these restrictions; it will help us to
understand whether any given implementation meets the restrictions.
Stephen Irons
More information about the Chchrobotics
mailing list