User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Tue Oct 18, 2016 12:32 pm

Anyone care to propose "Round 2" ?
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Tue Oct 18, 2016 12:37 pm

gregeric wrote:If your flight lands at either midday or midnight, you would be ill-advised to arrange for me to pick you up & quote me the time as 12AM or 12PM.
That's how it works. It makes sense because every second after 12:00:00 is after noon (post meridian) 12:00:01 (PM) is definitely not morning. Numbering of centuries can be similarly confusing with 1901 being the start of the twentieth century, not the nineteenth.

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Tue Oct 18, 2016 12:43 pm

PeterO wrote:Anyone care to propose "Round 2" ?
PeterO

How about:

A simple and easily extensible command interpreter.

Hold the position of a hypothetical bot in integer variables X and Y.
Decode command stings and apply values as increments to X,Y:

forward nn
back nn
left nn
right nn

Where nn is an integer distance.
Assume movement is orthogonal with no rotation and no slippage.

User avatar
karrika
Posts: 1284
Joined: Mon Oct 19, 2015 6:21 am
Location: Finland

Re: How would you ...... in C ?

Tue Oct 18, 2016 12:54 pm

And for all you pointer and malloc fans here is my entry ;)

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TIME_STRING_LEN 40

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

  for (hours = 0; hours < 24; hours++) {
    buf = calloc(1, TIME_STRING_LEN);
    if (buf) {
      int shown_hours;
      shown_hours = hours % 12;
      if (!shown_hours) shown_hours = 12;
      if (shown_hours > 9) {
        *buf = '1';
      } else {
        *buf = ' ';
      }
      *strchr(buf, 0) = '0' + (shown_hours % 10);
      puts(strcat(buf, (hours < 12) ? " AM" : " PM"));
      free(buf);
    }
  }
}
karkak@desktop:~$ gcc main.c
karkak@desktop:~$ ./a.out
12 AM
1 AM
2 AM
3 AM
4 AM
5 AM
6 AM
7 AM
8 AM
9 AM
10 AM
11 AM
12 PM
1 PM
2 PM
3 PM
4 PM
5 PM
6 PM
7 PM
8 PM
9 PM
10 PM
11 PM

User avatar
Paeryn
Posts: 3091
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: How would you ...... in C ?

Tue Oct 18, 2016 12:57 pm

PeterO wrote:
Paeryn wrote:Not a nice example, but without using ?:

Code: Select all

#define _GNU_SOURCE
It works so it must be allowed but I think because (to quote the man page) "These functions are GNU extensions, not in C or POSIX. " you must lose a point or two ;)
PeterO
[pedantic] But you never said that we couldn't use GNU extensions. [/pedantic] ;)

It was only to have a safer sprintf(), though if you're docking me points I should probably be docked some for not checking the return of asprintf() too on the unlikely chance that there wasn't enough memory to allocate the few bytes (and to return null in such a case, and then check the return value before trying to print it). :oops:
She who travels light — forgot something.
Please note that my name doesn't start with the @ character so can people please stop writing it as if it does!

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Tue Oct 18, 2016 1:33 pm

Paeryn wrote: though if you're docking me points I should probably be docked some for not checking the return of asprintf() too on the unlikely chance that there wasn't enough memory to allocate the few bytes (and to return null in such a case, and then check the return value before trying to print it). :oops:
Ah, but you got more extra points for using the safe string printf :-)
And who ever checks return values like that.... If it failed something much more serious has already gone wrong or is about to go wrong :D
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ? Round2

Tue Oct 18, 2016 1:41 pm

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <string.h>

struct command
{
    char *text;
    void (*handler)(int n);
};

GSList *commands = NULL;
int x = 0;
int y = 0;

void addCommand(char *text,void (*handler)(int n))
{
    struct command *cmd;

    cmd = (struct command *) malloc(sizeof(struct command));
    cmd->text = strdup(text);
    cmd->handler = handler;

    commands = g_slist_prepend(commands,cmd);
}

void doForward(int steps)
{
    printf("%s called %d steps\n",__FUNCTION__,steps);
    x += steps;
}

void doBack(int steps)
{
    printf("%s called %d steps\n",__FUNCTION__,steps);
    x -= steps;
}

void doLeft(int steps)
{
    printf("%s called %d steps\n",__FUNCTION__,steps);
    y += steps;
}

void doRight(int steps)
{
    printf("%s called %d steps\n",__FUNCTION__,steps);
    y -= steps;
}


void doCommand(char *cmdText,int steps)
{
    GSList *cmd;

    for(cmd = commands; cmd != NULL; cmd = g_slist_next(cmd))
    {
        if(strcmp(((struct command*)cmd->data)->text,cmdText) == 0)
        {
            (((struct command*)cmd->data)->handler)(steps);
            break;
        }
    }
    if(cmd == NULL)
        printf("Unregognised command (%s)\n",cmdText);
}

char *commandStrings[] =
{ "left 100","right 200","forward 10","back 9","up","up 90",NULL};

int main(void)
{
    int stringNumber;
    char *cmdString;
    char cmdText[100];
    int steps;
        
    addCommand("forward",doForward);
    addCommand("back",doBack);
    addCommand("left",doLeft);
    addCommand("right",doRight);

    stringNumber = 0;
    while((cmdString = commandStrings[stringNumber]) != NULL)
    {
        if( sscanf(cmdString,"%99s %d",cmdText,&steps) != 2)
        {
            printf("Invalid command format (%s)\n",cmdString);
        }
        else
        {
            doCommand(cmdText,steps);
            printf("poition is (%d,%d)\n",x,y);
        }
        stringNumber += 1;
    }
    return 0;
}
Compile with

Code: Select all

 
gcc -Wall -Wextra -o round2 round2.c $(pkg-config --cflags --libs glib-2.0)
Output

Code: Select all

doLeft called 100 steps
poition is (0,100)
doRight called 200 steps
poition is (0,-100)
doForward called 10 steps
poition is (10,-100)
doBack called 9 steps
poition is (1,-100)
Invalid command format (up)
Unregognised command (up)
poition is (1,-100)

Variable names are all a bit too similar, and it could do with a few comments, and X / Y axes may be less than obvious (but they weren't specified) ;)
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4257
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: How would you ...... in C ?

Tue Oct 18, 2016 3:22 pm

I'll wait until I get home to debug and finish it, but something like:

Code: Select all

struct fred
{
    char* command;
    int deltaX, deltaY;
} table[] = { {"forward", 1, 0}, {"left", 0,1},...}';

int X = 0, Y = 0;

int main()
{
    char c[256];
    int n;

    while (scanf("%s %d\n", c, n) == 2)
    {
         for (int i = 0; i < sizeof(table)/sizeof(table[0]); i++)
            if (strcmp(c, table[i].command) == 0)
            {
                 X += table[i].deltaX;
                 Y += table[i].deltaY;
                break;
            }
    }
    printf("Final position %d, %d\n", X, Y);
}

User avatar
Paeryn
Posts: 3091
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: How would you ...... in C ?

Tue Oct 18, 2016 4:21 pm

Similar to PeterO but without using glib (I "borrowed" a bit of PeterO's code)

Code: Select all

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct bot_t {
    struct command_t *commands;
    int x;
    int y;
} bot_t;

typedef void (*command_f)(bot_t *self, int increment);

typedef struct command_t {
    struct command_t *next;
    const char *command_str;
    command_f command_func;
} command_t;

static void botPrint(bot_t *self, const char *dir, int incr)
{
    printf("Moving %s by %d to (%d, %d)\n", dir, incr, self->x, self->y);
}

static void botLeft(bot_t *self, int increment)
{
    self->x -= increment;
    botPrint(self, "left", increment);
}

static void botRight(bot_t *self, int increment)
{
    self->x += increment;
    botPrint(self, "right", increment);
}

static void botForward(bot_t *self, int increment)
{
    self->y += increment;
    botPrint(self, "forward", increment);
}

static void botBack(bot_t *self, int increment)
{
    self->y -= increment;
    botPrint(self, "back", increment);
}

// Return pointer to a new bot at (0,0), or NULL if no memory
bot_t *botInitialise()
{
    bot_t *bot = malloc(sizeof *bot);
    if (bot) {
        bot->commands = NULL;
        bot->x = bot->y = 0;
    }
    return bot;
}

// Free all memory allocated to a bot
bot_t *botDelete(bot_t *bot)
{
    if (bot) {
        command_t *cmd = bot->commands;
        while (cmd) {
            command_t *next = cmd->next;
            free((void*)cmd->command_str);
            free(cmd);
            cmd = next;
        }
        free(bot);
    }
}

// Return 0 on success, 1 if anything went wrong
int botCommand(bot_t *bot, const char *instruction)
{
    if (!bot) {
        fputs("Null bot pointer\n", stderr);
        return 1;
    }
    if (!bot->commands) {
        fputs("Bot knows no commands\n", stderr);
        return 1;
    }

    char instr[100];
    int incr;
    
    if (sscanf(instruction, "%99s %d", instr, &incr) != 2) {
        fprintf(stderr, "Invalid command: %s\n", instruction);
        return 1;
    }
    
    command_t *cmd;
    for (cmd = bot->commands; cmd; cmd = cmd->next) {
        if (!strcmp(instr, cmd->command_str)) {
            cmd->command_func(bot, incr);
            return 0;
        }
    }
    fprintf(stderr, "Unknown command: %s\n", instruction);
    return 1;
}

// Add a new command to the bot, do nothing if null pointer for bot
void botNewCommand(bot_t *bot, const char *instruction, command_f func)
{
    command_t *command;

    if (bot) {
        command = (command_t*)&bot->commands;

        while (command->next)
            command = command->next;

        command = command->next = malloc(sizeof *command);
        command->command_str = strdup(instruction);
        command->command_func = func;
    }
}

char *commandStrings[] =
{ "left 100","right 200","forward 10","back 9","up","up 90",NULL};

int main()
{
    bot_t *bot = botInitialise();
    if (!bot) {
        fputs("Error creating bot\n", stderr);
        exit(EXIT_FAILURE);
    }
        
    botNewCommand(bot, "left", &botLeft);
    botNewCommand(bot, "right", &botRight);
    botNewCommand(bot, "forward", &botForward);
    botNewCommand(bot, "back", &botBack);

    char **commandList = commandStrings;
    char *commandStr;
    
    while ((commandStr = *commandList++) != NULL) {
        botCommand(bot, commandStr);
    }

    botDelete(bot);

    return EXIT_SUCCESS;
}
Output of program

Code: Select all

paeryn@perivor ~/Public/po $ gcc interp.c -Wall -Wextra -o interp
paeryn@perivor ~/Public/po $ ./interp 
Moving left by 100 to (-100, 0)
Moving right by 200 to (100, 0)
Moving forward by 10 to (100, 10)
Moving back by 9 to (100, 1)
Invalid command: up
Unknown command: up 90
paeryn@perivor ~/Public/po $ 
<Edit> Fixed memory allocation - I pasted an older version with incorrect sizeof. Plus moved initialisation to its own function and added a bit more error checking.
Last edited by Paeryn on Tue Oct 18, 2016 10:31 pm, edited 3 times in total.
She who travels light — forgot something.
Please note that my name doesn't start with the @ character so can people please stop writing it as if it does!

ewaller
Posts: 32
Joined: Tue Oct 04, 2016 5:24 pm

Re: How would you ...... in C ?

Tue Oct 18, 2016 4:21 pm

Code: Select all

ewaller@turing ~ 1005 %cat ampm.c
#include <stdio.h>
void convert(int x)
{

  printf("%i %cM\n",x?(x<13)?x:x-12:12,(x<12)?'A':'P');
}

int main(int argc, char **argv)
{
    int i;
    for (i=0; i<24 ; i++)
      convert(i);
}
ewaller@turing ~ 1006 %gcc ampm.c
ewaller@turing ~ 1007 %./a.out
12 AM
1 AM
2 AM
3 AM
4 AM
5 AM
6 AM
7 AM
8 AM
9 AM
10 AM
11 AM
12 PM
1 PM
2 PM
3 PM
4 PM
5 PM
6 PM
7 PM
8 PM
9 PM
10 PM
11 PM
ewaller@turing ~ 1008 %
Or, if you want something that is much easier to read

Code: Select all

ewaller@turing ~ 1009 %cat ampm.c
#include <stdio.h>

static char* lookup[]=
  {
    "12 AM"," 1 AM"," 2 AM"," 3 AM"," 4 AM"," 5 AM",
    " 6 AM"," 7 AM"," 8 AM"," 9 AM","10 AM","11 AM",
    "12 PM"," 1 PM"," 2 PM"," 3 PM"," 4 PM"," 5 PM",
    " 6 PM"," 7 PM"," 8 PM"," 9 PM","10 PM","11 PM"
  };

int main(int argc, char **argv)
{
    int i;
    for (i=0; i<24 ; i++)
      printf("%s\n",lookup[i]);
}

ewaller@turing ~ 1010 %gcc ampm.c
ewaller@turing ~ 1011 %./a.out
12 AM
 1 AM
 2 AM
 3 AM
 4 AM
 5 AM
 6 AM
 7 AM
 8 AM
 9 AM
10 AM
11 AM
12 PM
 1 PM
 2 PM
 3 PM
 4 PM
 5 PM
 6 PM
 7 PM
 8 PM
 9 PM
10 PM
11 PM
ewaller@turing ~ 1012 %
Last edited by ewaller on Tue Oct 18, 2016 9:15 pm, edited 2 times in total.

User avatar
gordon@drogon.net
Posts: 2023
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website Twitter

Re: How would you ...... in C ?

Tue Oct 18, 2016 4:38 pm

PiGraham wrote:
PeterO wrote:Anyone care to propose "Round 2" ?
PeterO

How about:

A simple and easily extensible command interpreter.

Hold the position of a hypothetical bot in integer variables X and Y.
Decode command stings and apply values as increments to X,Y:

forward nn
back nn
left nn
right nn

Where nn is an integer distance.
Assume movement is orthogonal with no rotation and no slippage.
Careful here... Next thing you know you'll end up writing a Turing complete turtle graphics interpreter, complete with an all-purpose symbolic instruction code for beginners to go with it....

-Gordon
--
Gordons projects: https://projects.drogon.net/

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4257
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: How would you ...... in C ?

Tue Oct 18, 2016 5:22 pm

A few minor fixes, plus learning again why nobody ever uses scanf.

Code: Select all

 #include <stdio.h>
 
 struct fred
    {
        char* command;
        int deltaX, deltaY;
    } table[] = { {"forward", 1, 0}, {"left", 0,-1}, {"back", -1,0}, {"right", 0,1} };

    int X = 0, Y = 0;

    int main()
    {
        char c[256], buff[256];
        int n, i;

        while (fgets(buff, sizeof(buff), stdin) && sscanf(buff, "%s%d", c, &n) == 2)
        {
             for (i = 0; i < sizeof(table)/sizeof(table[0]); i++)
                if (strcmp(c, table[i].command) == 0)
                {
                     X += n*table[i].deltaX;
                     Y += n*table[i].deltaY;
                    break;
                }
        }
        printf("Final position %d, %d\n", X, Y);
    }

Code: Select all

$ ./robot
forward 5
right 8
back 1
left 2
Final position 4, 6

ewaller
Posts: 32
Joined: Tue Oct 04, 2016 5:24 pm

Re: How would you ...... in C ?

Tue Oct 18, 2016 8:25 pm

Code: Select all

ewaller@turing ~ 1009 %cat move.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 10

typedef struct {int dx; int dy;} deltaStruct;
typedef struct {int x; int y;} location;
static struct {char* command; deltaStruct delta;} DecoderRing[]=
  {
    {"forward" ,{ 1 , 0 }},
    {"back"    ,{-1 , 0 }},
    {"left"    , {0 ,-1 }},
    {"right"   , {0 , 1 }},
    {0         , {0 , 0 }}
  };

int parseCommand(char* theCommand)
{
  int i;
  for (i=0 ; DecoderRing[i].command ; i++)
    if (!strcmp(DecoderRing[i].command,theCommand))
      return i;
  printf("Command '%s' not recognized\n",theCommand);
  return -1;
}

void Move(char* theRawCommand,location* theLocation)
{
  char theCommand[MAX_SIZE];
  char theLengthStr[MAX_SIZE];
  int size = 0;
  char *p = theRawCommand;
  char *q = theCommand;

  while (*p == ' ')
    p++;
  while (*p && *p != ' ' && ++size < MAX_SIZE)
    *(q++) = *(p++);
  size=0;
  *q=0;
  q = theLengthStr;
  while (*p == ' ')
    p++;
  while (*p && *p != ' ' && ++size < MAX_SIZE)
    *(q++) = *(p++);
  *q=0;
  if (parseCommand(theCommand) < 0)
    return;
  theLocation->x += DecoderRing[parseCommand(theCommand)].delta.dx
    * atoi(theLengthStr);
  theLocation->y += DecoderRing[parseCommand(theCommand)].delta.dy
    * atoi(theLengthStr);
}

void Report(location theLocation)
{
  printf ("Moved to %i,%i \n",theLocation.x,theLocation.y);
}


char* testVector[] =
  {
    "right 10",
    "forward 20",
    "up 45",
    "left   20",
    "  back 30",
    "right face",
    "ThisIsTooLong",
    0
  };

int main(int argc, char ** argv)
{
  location theLocation = {0,0};
  int i;

  Report (theLocation);
  for (i=0 ; testVector[i] ; i++)
    {
      Move(testVector[i],&theLocation);
      Report(theLocation);
    }
}

ewaller@turing ~ 1010 %gcc move.c
ewaller@turing ~ 1011 %./a.out
Moved to 0,0
Moved to 0,10
Moved to 20,10
Command 'up' not recognized
Moved to 20,10
Moved to 20,-10
Moved to -10,-10
Moved to -10,-10
Command 'ThisIsToo' not recognized
Moved to -10,-10
ewaller@turing ~ 1012 %

User avatar
DougieLawson
Posts: 40254
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: How would you ...... in C ?

Tue Oct 18, 2016 8:44 pm

Code: Select all

#include <stdio.h>
#include <string.h>
int main (void)
{
  int i;
  int j;
  char p[3];
  for (i=0; i<24; i++)
  {
    j = (i == 0) ? i+12 : i;
    j = (i > 12) ? j-12 : j;
    memcpy(p, (i < 12) ? "AM" : "PM", sizeof p);
    printf ("Hour 24: %d Hour: 12: %d%s\r\n", i, j, p);
  }
  return 0;
}
is that suitably ugly?
Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Tue Oct 18, 2016 8:52 pm

This is obviously MSVC MFC code so it won't compile or run on Pi. The code works, but not tested in this edited form.
It would be easy to translate for gcc and std::string

It uses a statically initialised array for the command table. The code adapts to whatever size it is and we don't need dynamic allocation since command functions are defined at compile time. It can be declared static const. On a microcontroller the table could remain in program memory (flash) without consuming RAM. Not an issue on PC or Pi.

The was written to handle socket comms and I pass the command string itself and a socket reference to the command function to allow further parsing of parameters and command-specific replies.
Since the command function has the command string it can parse it for parameters so we can have any parameters we like per command.

Code: Select all

typedef struct{
char* Str;            /* the command string */
void  (*Fun)(CMySocket *sock , CStringA &cmd);   /* the handler function */
}CmdStruct;

CmdStruct Commands[]={
	{"reset",CMySocket::Cmd_Reset},
	{"get image",		CMySocket::Cmd_GetImage},
	{"set event port",	CMySocket::Cmd_SetEventPort},
	{"get settings",	CMySocket::Cmd_GetSettings}
}

// Later on, when a command string is available...

	char command[COMMANDLEN];
	int num;					// number of bytes received. 0 = error
	int ncmds = sizeof (Commands)/sizeof(CmdStruct);

	num = Receive(command,COMMANDLEN);			// get the command string (from socket, pipe stream etc
	if(num<=0) 
	{
		DWORD err = GetLastError();
		TRACE ("Error [%d] in OnRecieve\n",err);
		return;
	}
	command[num]=0;    //Ensure null termination

	CStringA Commstr("Command ");
	CStringA Recstr(command);
	Recstr.MakeLower();
	for(int cmdi=0;cmdi<ncmds;cmdi++)
	{
		if(CMP_CMD(Commands[cmdi].Str,Recstr))
		{
			(Commands[cmdi].Fun)(this,Recstr);
			break;
		}
	}

// Sample command function

void CMySocket::Cmd_SetEventPort(CMySocket *sock,CStringA &cmd)
{
	int tmp;
	UINT iPort;
	CString ip;
	if(ReadParam(cmd,"port","%d",&tmp))
	{
		sock->m_pApp->m_iEventPort = tmp;
		sock->GetPeerName(ip,iPort);
		sock->m_pApp->m_sEventIP = ip;
		sock->SendMsg("Port Set");
	}
	else
	{
		sock->SendMsg("Port Error");
	}
}

// Function to extract names parameters from the string

// This macro isn't really necessary, just a bit shorter
#define CMP_CMD(cmd,x)	(0==strncmp(cmd,x,strlen(cmd)))

//This scans the string for named parameters and converts the value according to a single sscanf style format pattern.
// It's a bit inefficient since it scans the whole string up to the named parameter for every parameter, but this does mean that parameter order doesn't matter. It could do with some type safety for the pointer type vs. format character.
This uses sscanf but in another form I went for atoi, atof etc, to suit format specification.

BOOL ReadParam(LPCSTR str,LPCSTR pname,LPCSTR fmt,LPVOID var)
{
	int ret;
	LPCSTR pos = strstr(str,pname);
	if(pos!=NULL)
	{
		pos += strlen(pname);
		ret = sscanf(pos,fmt,var);
		if (ret>=1)
			return TRUE;
	}
	return FALSE;
}


PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Tue Oct 18, 2016 8:54 pm

DougieLawson wrote:

Code: Select all

#include <stdio.h>
#include <string.h>
int main (void)
{
  int i;
  int j;
  char p[3];
  for (i=0; i<24; i++)
  {
    j = (i == 0) ? i+12 : i;
    j = (i > 12) ? j-12 : j;
    memcpy(p, (i < 12) ? "AM" : "PM", sizeof p);
    printf ("Hour 24: %d Hour: 12: %d%s\r\n", i, j, p);
  }
  return 0;
}
is that suitably ugly?
It's a bit long, isn't it? ;)

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Tue Oct 18, 2016 9:22 pm

PiGraham wrote:This is obviously MSVC MFC code so it won't compile or run on Pi.
If I can't compile it and run it, iit falls into the "doesn't work" category :roll:
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Wed Oct 19, 2016 8:39 am

PeterO wrote:
PiGraham wrote:This is obviously MSVC MFC code so it won't compile or run on Pi.
If I can't compile it and run it, iit falls into the "doesn't work" category :roll:
PeterO
Yep, just a potential discussion point, not a competition entry.
Do you want this topic to be just a list of working examples and exclude code snippets and other stuff? Pi only?

So, what's next?

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Wed Oct 19, 2016 8:46 am

PiGraham wrote:
PeterO wrote:
PiGraham wrote:This is obviously MSVC MFC code so it won't compile or run on Pi.
If I can't compile it and run it, iit falls into the "doesn't work" category :roll:
PeterO
Yep, just a potential discussion point, not a competition entry.
Do you want this topic to be just a list of working examples and exclude code snippets and other stuff? Pi only?

So, what's next?
I suppose it's to get ideas for example code to demonstrate the finer points of C programming :-) Working code is best, but testable snippets are OK too.

Since we seem to have done your "write an interpreter home work" :-) Round 3.......

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Wed Oct 19, 2016 9:20 am

PeterO wrote:
PiGraham wrote:Since we seem to have done your "write an interpreter home work" :-) Round 3.......

PeterO
I contributed something in good faith, code I have used in various projects over the years. I didn't spend a lot of time on it making it compile because I know it's working code, I don't have a lot of time free and I thought it might be of some interest. If people only want tested Pi code here that's fine, but you may get fewer contributions.

It might also be a good idea to avoid the snide and ill-judged comments about "home work".

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Wed Oct 19, 2016 9:43 am

PiGraham wrote:
PeterO wrote:Since we seem to have done your "write an interpreter home work" :-) Round 3.......

PeterO
I contributed something in good faith, code I have used in various projects over the years.
As was mine. The message parsing code came straight from a simple client/server library I've been using for at least 10 years.
I didn't spend a lot of time on it making it compile because I know it's working code, I don't have a lot of time free and I thought it might be of some interest. If people only want tested Pi code here that's fine, but you may get fewer contributions.
I think the focus should be one code that will run in a PI, after all that's why we're all here.

It might also be a good idea to avoid the snide and ill-judged comments about "home work".
It was a joke ! But you have to admit it IS the sort of thing that could be set as homework :-) <<< Smiley
I think it's only fair to post tested working code , otherwise what's the point ? As we've seen in another thread people who claim to understand C and post code snippets that they say support their point, but in fact they don't.
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Wed Oct 19, 2016 9:57 am

PeterO wrote: The message parsing code came straight from a simple client/server library I've been using for at least 10 years.
Quite, there are a lot of mature programmers here who will have a lot of code that could be relevant and a lot of it won't be in a form that will just compile and run as-is on Pi. It depending on what platform and libraries we have been using. Obviously we can re-write it if we have the time, but that may limit contributions.
Last edited by PiGraham on Wed Oct 19, 2016 10:09 am, edited 1 time in total.

PiGraham
Posts: 4208
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: How would you ...... in C ?

Wed Oct 19, 2016 10:08 am

Is there a good source of nice Python examples that would be a good basis for building a similar resource in C for Pi?

User avatar
PeterO
Posts: 5976
Joined: Sun Jul 22, 2012 4:14 pm

Re: How would you ...... in C ?

Wed Oct 19, 2016 10:27 am

PiGraham wrote:Is there a good source of nice Python examples that would be a good basis for building a similar resource in C for Pi?
I don't know, but I've not looked...... As a source of ideas for "Rounds" it could be helpful.

I don't know about you, but I find I have a quite different "mind set" when I'm writing Python to when I'm writing C.
Although the languages themselves have similarities, I find I chose one over the other depending on the type of task at hand.

For example I recently wrote some Python to take the output from a "locate" command that found all the files with picture (jpeg,jpeg,png) extensions.
Then it computed hashes for each file to detect duplicates of pictures which had different names, and also to find files with the same name which are actually different pictures.
I could have done it in C and it would have been much quicker to run, but it was much easier to write it in Python.

It's about having a good selection of tools in your programmer's tool box, and knowing which one to use in each situation otherwise this applies :
https://en.wiktionary.org/wiki/if_all_y ... ike_a_nail

As I said in another thread I don't think comparisons between C and other languages are a good idea as it presupposes knowledge of the other languages.

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

User avatar
JRV
Posts: 270
Joined: Mon Apr 02, 2012 1:39 pm
Location: Minneapolis, MN

Re: How would you ...... in C ?

Wed Oct 19, 2016 1:26 pm

Code: Select all

  printf("%02d:%02d", hour, minute); 
  if(hour<12) printf(" AM");  
  else printf(" PM");
I hate military time, I had enough of that when I was in the Army.

I refuse to use military time and I refuse to debug whitespace.

Return to “C/C++”