<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>assignment &#8211; Luxing Huang</title>
	<atom:link href="https://luxing.im/tag/assignment/feed/" rel="self" type="application/rss+xml" />
	<link>https://luxing.im</link>
	<description>Thoughs and things</description>
	<lastBuildDate>Sat, 12 Dec 2015 21:38:46 +0000</lastBuildDate>
	<language>en-CA</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
<site xmlns="com-wordpress:feed-additions:1">58771605</site>	<item>
		<title>Prefix expression conversion to Postfix and Infix</title>
		<link>https://luxing.im/prefix-expression-conversion-to-postfix-and-infix/</link>
					<comments>https://luxing.im/prefix-expression-conversion-to-postfix-and-infix/#respond</comments>
		
		<dc:creator><![CDATA[Luxing Huang]]></dc:creator>
		<pubDate>Fri, 29 Nov 2013 15:20:40 +0000</pubDate>
				<category><![CDATA[Learning Notes]]></category>
		<category><![CDATA[assignment]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[infix]]></category>
		<category><![CDATA[postfix]]></category>
		<category><![CDATA[prefix]]></category>
		<guid isPermaLink="false">http://blog.luxing.im/?p=206</guid>

					<description><![CDATA[There has been a question related with prefix to infix/postfix expression on the latest assignment in C. I managed to solve this puzzle, the whole assignment is here and you can take a peek at (Question 2). The whole resolving idea has been basically expressed in Jim&#8217;s description, using a recursive way to build a &#8230; <p class="link-more"><a href="https://luxing.im/prefix-expression-conversion-to-postfix-and-infix/" class="more-link">Continue reading<span class="screen-reader-text"> "Prefix expression conversion to Postfix and Infix"</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>There has been a question related with prefix to infix/postfix expression on the latest assignment in C. I managed to solve this puzzle, the whole assignment is <a href="http://socs.acadiau.ca/~jdiamond/comp2103/assignments/a12.pdf" target="_blank">here</a> and you can take a peek at (Question 2).<br />
<span id="more-206"></span><br />
The whole resolving idea has been basically expressed in Jim&#8217;s description, using a recursive way to build a tree, deal from left leaf to right leaf and printing out from bottom to top. This is code is my original piece, I might have a few presentation errors that not have matched with Jim&#8217;s requirements. Anyway, here is the whole code:</p>
<pre>
/*
 * File:        prefix.c
 * Author:      Luxing Huang
 * Date:        2013/11/24
 * Version:     1.0
 *
 * Purpose:     This programme will take in tokens from arguments or stdin to
 *              give back:
 *              1. postfix polish notation
 *              2. infix polish notation
 *              3. the result of the calculation (optional)
 *
 * Assumption:  User input will not exceed 256/2=128 chars.
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>

#define LIMIT 257

int pos;

typedef struct expression_tree_node
{
    struct expression_tree_node *leftnode;
    struct expression_tree_node *rightnode;
    union
    {
        int32_t left;
        char leftop[4];
    } left;

    union
    {
        int32_t right;
        char rightop[4];
    } right;

    union
    {
        char topop[4]; 
        int32_t top;
    } top;

    bool left_done;
    bool right_done;
} *node_T;

/*
 * Name:        convert
 * Purpose:     Convert from prefix expression to infix and postfix expression.
 * Arguments:   prefixin, postout, infixout, leaf1
 * Returns:     nothing
 * Modifies:    postout, infixout
 */
void
convert(char *prefixin, char *postout, char *infixout, node_T leaf1)
{
    int ret;
    node_T leaf2 = malloc(sizeof(struct expression_tree_node)); 
    char *tmp = calloc(LIMIT, sizeof(char));
    char *postoutl = calloc(LIMIT, sizeof(char));
    char *postoutr = calloc(LIMIT, sizeof(char));
    char *infixoutl = calloc(LIMIT, sizeof(char));
    char *infixoutr = calloc(LIMIT, sizeof(char));

    pos = 0;

    if (tmp == NULL || postoutl == NULL || postoutr == NULL || infixoutl == NULL
            || infixoutr == NULL)
    {
        fprintf(stderr, "Unable to calloc.\n");
        exit(-1);
    }


    /* Scanning in the top operator */
    if (leaf1->top.topop == 0)
    {
        ret = sscanf(prefixin, "%s", leaf1->top.topop);
        if (ret == 0)
        {
            fprintf(stderr, "Invalid expression.\n");
            exit(-1);
        }
        pos+= 2;
    }

    /* Scanning left tree */
    ret = sscanf(prefixin, "%d", &leaf1->left.left);
    if (ret == 0)
    {
        ret = sscanf(prefixin, "%s", leaf1->left.leftop);
        if (ret == EOF)
        {
            fprintf(stderr, "Insufficient arguments!\n");
            exit(-1);
        }
        pos += 2;
        strncpy(leaf2->top.topop, leaf1->left.leftop, sizeof(int32_t));
        leaf1->leftnode = leaf2;
        convert(prefixin + pos, postoutl, infixoutl, leaf2);
        pos += 2;
    }
    else if (ret == EOF)
    {
        fprintf(stderr, "Insufficient arguments!\n");
        exit(-1);
    }
    else
    {
        pos += 2;
        leaf1->left_done = true;
    }

    /* Scanning Right tree */
    ret = sscanf(prefixin + pos, "%d", &leaf1->right.right);
    if (ret == 0)
    {
        ret = sscanf(prefixin + pos, "%s", leaf1->right.rightop);
        if (ret == EOF)
        {
            fprintf(stderr, "Insufficient arguments!\n");
            exit(-1);
        }
        pos += 2;
        strncpy(leaf2->top.topop, leaf1->right.rightop, sizeof(int32_t));
        leaf1->rightnode = leaf2;
        convert(prefixin + pos, postoutr, infixoutr, leaf2);
        pos += 2;
    }
    else if (ret == EOF)
    {
        fprintf(stderr, "Insufficient arguments!\n");
        exit(-1);
    }
    else
    {
        leaf1->right_done = true;
        pos += 2;
    }

    /* Setting up Output */
    if (leaf1->left_done == true)
    {
        if (leaf1->right_done == true)
        {
            sprintf(tmp, "%d %d %s ", leaf1->left.left, leaf1->right.right,
                    leaf1->top.topop);
            strncpy(postout, tmp, LIMIT);
            sprintf(tmp, "(%d %s %d)", leaf1->left.left, leaf1->top.topop,
                    leaf1->right.right);
            strncpy(infixout, tmp, LIMIT);
        }
        else
        {
            sprintf(tmp, "%d %s %s", leaf1->left.left, postoutr,
                    leaf1->top.topop);
            strncpy(postout, tmp, LIMIT);
            sprintf(tmp, "(%d %s %s)", leaf1->left.left, leaf1->top.topop,
                    infixoutr);
            strncpy(infixout, tmp, LIMIT);
        }
    }
    else
    {
        if (leaf1->right_done == true)
        {
            sprintf(tmp, "%s %d %s", postoutl, leaf1->right.right,
                    leaf1->top.topop);
            strncpy(postout, tmp, LIMIT);
            sprintf(tmp, "(%s %s %d)", infixoutl, leaf1->top.topop, 
                    leaf1->right.right);
            strncpy(infixout, tmp, LIMIT);
        }
        else 
        {
            sprintf(tmp, "%s %s %s", postout, postout, leaf1->top.topop);
            strncpy(postout, tmp, LIMIT);
            sprintf(tmp, "(%s %s %s)", infixout, leaf1->top.topop, infixout);
            strncpy(infixout, tmp, LIMIT);
        }
    }
}

int
main(int argc, char *argv[])
{
    char *prefixin = calloc(LIMIT,  sizeof(char));
    char *postout = calloc(LIMIT,  sizeof(char));
    char *infout = calloc(LIMIT,  sizeof(char));
    char arguments[] = "echo '";
    char bc[] = "' | bc ";
    node_T start_of_tree;
    start_of_tree = malloc(sizeof(struct expression_tree_node));

    if (prefixin == NULL || postout == NULL || infout == NULL || 
        start_of_tree == NULL)
    {
        fprintf(stderr, "Unable to malloc.\n");
        return EXIT_FAILURE;
    }
    int i, ret, count;
    count = 2;

    if (argc == 1)
    {
        if (isatty(fileno(stdin)))
        {
            printf("Please enter your expression: ");
        }
        fgets(prefixin, LIMIT, stdin);
    }
    else
    {
        for (i = 1; i < argc; i++)
        {
            strcat(prefixin, argv[i]);
            strcat(prefixin, " ");
        }
    }

    ret = sscanf(prefixin, "%d", &#038;start_of_tree->top.top);
    if (ret == 1)
    {
        printf("Postfix: %d\n", start_of_tree->top.top);
        printf("Infix:   (%d)\n", start_of_tree->top.top);
        printf("Result:  %d\n", start_of_tree->top.top);
        return EXIT_SUCCESS;
    }
    else
    {
        ret = sscanf(prefixin, "%s", start_of_tree->top.topop);
        if (ret == 0)
        {
            fprintf(stderr, "Invalid expression!\n");
            return EXIT_FAILURE;
        }
    }

    convert(prefixin + count, postout, infout, start_of_tree);

    printf("Postfix: %s\n", postout);
    printf("Infix:   %s\n", infout);
    printf("Result:  ");
    fflush(stdout);

    strcat(arguments, infout);
    strcat(arguments, bc);
    system(arguments);
    return EXIT_SUCCESS;
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://luxing.im/prefix-expression-conversion-to-postfix-and-infix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">206</post-id>	</item>
		<item>
		<title>A5P1</title>
		<link>https://luxing.im/a5p1/</link>
					<comments>https://luxing.im/a5p1/#respond</comments>
		
		<dc:creator><![CDATA[Luxing Huang]]></dc:creator>
		<pubDate>Sat, 05 Oct 2013 15:33:00 +0000</pubDate>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[assignment]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[homework]]></category>
		<guid isPermaLink="false">http://blog.luxing.im/?p=31</guid>

					<description><![CDATA[&#160; For thoses who don&#8217;t know what a5p1 means, it means Assignment 5, Problem 1. Yesterday, my professor Jim added a new assignment for us to do. I am going to talk about the first in this article. I am not a good coder and I just started learning C this term. Still, I am &#8230; <p class="link-more"><a href="https://luxing.im/a5p1/" class="more-link">Continue reading<span class="screen-reader-text"> "A5P1"</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>&nbsp;</p>
<p>For thoses who don&#8217;t know what a5p1 means, it means Assignment 5, Problem 1.</p>
<p>Yesterday, my professor Jim added a new assignment for us to do. I am going to talk about the first in this article.</p>
<p><span id="more-31"></span></p>
<p>I am not a good coder and I just started learning C this term. Still, I am trying to solve the puzzle as best I can. I know it is not a good style to put everything under main(), but since it&#8217;s a simple and straightforward problem, please accept my messy style of coding.</p>
<p>You can view the question <a href="http://file.luxing.im/dirLIST_files/download.php?file=Li9zaGFyZS9hNS5wZGY=" target="_blank">here</a>. I started writing the first problem this morning and I think I have finished this problem at the noon. (Just before the time I was writing this article.)</p>
<p>If you get a 404 error, that means this term has finished, you can get the problem sets by emailing me.</p>
<p>Things need attention:</p>
<p>1. I need to justify what format the input/output is:</p>
<pre>input:
N
Year(%d) Month(%s) Day(%d)
....

output:
Year(%d) Month(%d) Day(%s)</pre>
<p>I happened to mixed the order up during programming, but it wasn&#8217;t a big deal.</p>
<p>2. It&#8217;s important to know that the Highwings calendar count from 0 in <em>day</em> section but Lowwings calendar count start from 1 in <em>month</em> section.</p>
<p>3. Those calendar systems have different days per year. Highwings has <img decoding="async" src="https://s0.wp.com/latex.php?latex=12%5Ctimes30%2B20+%3D+380&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="12&#92;times30+20 = 380" class="latex" /> days per year and Lowwings has <img decoding="async" src="https://s0.wp.com/latex.php?latex=20%5Ctimes12%3D240&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="20&#92;times12=240" class="latex" /> days per year, we can write a macro for further use.</p>
<pre>#define TOTAL_DAYS_PERYR_HIGHWING (12 * 30 + 20)
#define TOTAL_DAYS_PERYR_LOWWING (20 * 12)</pre>
<p>The structure is simple, parse every line until <em>N</em> is reached using a for loop. Using getchar and scanf to read the values from <span style="color: #ff9900;">stdin</span>, assign it to corresponding values. Professor has already talked about this in <a href="http://pastebin.com/jTsJ1byS" target="_blank">a3p1</a>, we can extract his ideas and implement them into our code.</p>
<p>Why we don&#8217;t just parse the whole line all-together using</p>
<pre> scanf("%d %s %D\n", &h_yr, &h_m, &h_d)</pre>
<p>You&#8217;ll never know what the user is going to type in, therefore the <span style="color: #ff9900;">stdin</span> might not be what you expected. This is for error checking which I&#8217;ll talk about it later.</p>
<p>When you have all the correct values assigned to correct variables, then how to convert it to Lowwings Calendar system?</p>
<p>What I did was to find the total days, it should be the only thing in common between these 2 systems of calendar, I call the variable <em>unify_day</em>.</p>
<p>Now things are getting clearer.</p>
<p>In this case,</p>
<pre>1 charlie 17</pre>
<p>charlie is the <img decoding="async" src="https://s0.wp.com/latex.php?latex=3%5E%7Brd%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="3^{rd}" class="latex" /> month in Year 1, but the <img decoding="async" src="https://s0.wp.com/latex.php?latex=3%5E%7Brd%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="3^{rd}" class="latex" /> month has not passed, so we only need to count the first 2 months into <em>unify_day</em>, then calculate the day/month/year in Lowwings system.</p>
<p>Finally you need to reset <em>unify_day</em> to 0 at the end of loop.</p>
<p>When you try to divide a number with 12, and if the remainder is 0, it doesn&#8217;t mean that it&#8217;s the start of next month, it&#8217;s the end of the previous month. So I have put zulu first in my string array.</p>
<pre>*lowwing_day_names[] = {"zulu", "november", "oscar", "papa", "quebec",
        "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray"};</pre>
<p>The error detect part, which types of error have I considered?</p>
<pre>
(a). When N = 0.
(b). When N &lt; next few lines. (When N &gt; next few lines I just ignore the rest)
(c). Invalid data:
   i. When !isdigit(N)
   ii. !isdigit(h_day)
   iii. !isdigit(h_yr)
(d). spaces/tabs as seperator.
</pre>
<p>Programme ends whenever an error occurs.</p>
<pre>
/*
 * File:    lightplane.c
 * Author:  Luxing Huang
 * Version: 1.0
 *
 * Purpose:
 * When we have 2 different calendar systems, we need to translate the old one
 * to the new one. 
 *
 * Here we have an old system called Highwings: A year with 13 month, 30 days 
 * for the 1-12th month, and 20 days for the 13th month. We will have 30x12+20
 * = 380 days a year. Every month has its own name.
 *
 * And the second system is 240 days a year. We have 20 months with 12 days in
 * each month. Every day in each month has its own name. This system is called
 * Lowwings.
 *
 * The input format is:
 * N
 * Year(%d) Month(%s) Day(%d)
 *
 * The output format is:
 * Year(%d) Month(%d) Day(%s)
 */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define CHAR_LENGTH 128
#define TOTAL_DAYS_PERYR_HIGHWING (12 * 30 + 20)
#define TOTAL_DAYS_PERYR_LOWWING (20 * 12)

int
main(int argc, char *argv[])
{
    /*
     * Structure:
     * 1. scan the input, preferrably using getchar then scanf
     * 2. Convert Highwing days to unify_day.
     * 3. Error detect:
     *  a. N < next a few lines. If > I just ignore the rest.
     *  b. Invalid data:
     *      (a) when it should be a number, it's a char.
     *      (b) after year we have more char rather than \n.
     * 4. Calculate the unify day to Lowwing system.
     */
    unsigned int i, unify_day = 0, highwing_year = 0, highwing_day = 0, 
                 lowwing_year = 0, lowwing_month = 0, lowwing_day = 0;
    int highwing_month = -1, entries = 0, c = 0;
    char highwing_month_name[CHAR_LENGTH] = "";
    char *highwing_compare[] = {"alpha", "bravo", "charlie", "delta", "echo", 
        "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima", "mike"},
         *lowwing_day_names[] = {"zulu", "november", "oscar", "papa", "quebec", 
        "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray"};
    
    /* Ignoring spaces if have any */
    scanf("%*[ \t]");

    /* check if is a digit */
    c = getchar();
    if (!isdigit(c))
    {
        fprintf(stderr, "You need to put a positive integer in the first " 
                "line!\n");
        return EXIT_FAILURE;
    }
    else
        ungetc(c, stdin);

    scanf("%d", &entries);
    if (entries <= 0)
    {
        fprintf(stdout, "Nothing to calculate!\n");
        return EXIT_SUCCESS;
    }
    else
    {
        /* 
         * Error detect for:
         * N more_char_here
         */
        scanf("%*[ \t]");
        c = getchar();
        if (c == EOF)
        {
            fprintf(stderr, "Where are your next lines?\n");
            return EXIT_FAILURE;
        }
        else if (c != '\n')
        {
            fprintf(stderr, "You should not input anything "
                            "behind %d!\n", entries);
            return EXIT_FAILURE;
        }

        /* We need to have a loop for entries time */
        for (i = 0; i < entries; i++)
        {
            /* We get year first, ignoring spaces */
            scanf("%*[ \t]");
            c = getchar();
            if (c == EOF)
            {
                fprintf(stderr, "Where's the %d(th) set of data?\n", i+1);
                return EXIT_FAILURE;
            }
            else if (!isdigit(c))
            {
                fprintf(stderr, "This is not a valid day!\n");
                return EXIT_FAILURE;
            }
            ungetc(c, stdin);
            scanf("%d", &#038;highwing_year);

            /* Now the name (string) for highwing month */
            int m;
            c = getchar();
            if (c != ' ' &#038;&#038; c != '\t')
                fprintf(stderr, "Your input format is wrong but we'll " 
                        "proceed anyway.\n");
            scanf("%*[ \t]");

            scanf("%s", highwing_month_name);
            for (m = 0; m <= 13; m++)
            {
                if (strcmp(highwing_month_name, highwing_compare[m]) == 0)
                {
                    /* Array of strings position start from 0 */
                    highwing_month = m;
                    break;
                }
            }
            if (highwing_month == -1)
            {
                fprintf(stderr, "Invalid month name.\n");
                return EXIT_FAILURE;
            }

            /* 
             * Let's now scan the day
             * First we need to make sure that the first character is a digit.
             */
            c = getchar();
            if (c != ' ' &#038;&#038; c != '\t')
                fprintf(stderr, "Your input format is wrong but we'll "
                        "proceed anyway.\n");

            scanf("%*[ \t]");
            c = getchar();
            if (!isdigit(c))
            {
                fprintf(stderr, "Invalid input!\n");
                return EXIT_FAILURE;
            }
            else
                ungetc(c, stdin);

            scanf("%d", &#038;highwing_day);

            if (highwing_day > 29)
            {
                fprintf(stderr, "You shouldn't input more than 30 days!\n");
                return EXIT_FAILURE;
            }
            highwing_day++;

            /* 
             * We need to make sure about the boundary values, 
             * In this case, the last day of mike is 20th
             */
            if (highwing_month == 12 && highwing_day > 20)
            {
                fprintf(stderr, "You cannot input 20 or more in day in " 
                        "Mike!\n");
                return EXIT_FAILURE;
            }

            /* ignoreing the spaces afterwards */
            scanf("%*[ \t]");

            /* Make sure that we have a nextline in the end */
            c = getchar();
            if (!(c == '\n'))
            {
                fprintf(stderr, "Nothing behind %d please!", highwing_day);
                return EXIT_FAILURE;
            }
            /* 
             * Once it is all done, we add the current inputs to unify_day.
             * Every Highwing month has 30 days except the last one.
             */
            unify_day = highwing_year * TOTAL_DAYS_PERYR_HIGHWING + highwing_month * 30
                        + highwing_day;

            /* 
             * From unify_day we need to calculate the year for Lowwing calendar
             */
            lowwing_year = unify_day / TOTAL_DAYS_PERYR_LOWWING;
            unify_day -= lowwing_year * TOTAL_DAYS_PERYR_LOWWING;

            /* We need to have lowwing_month at this point. */
            lowwing_month = unify_day / 12;
            unify_day -= lowwing_month * 12;

            if ((unify_day % 12) == 0)
                lowwing_month--;

            /* Now the day */
            lowwing_day = unify_day;

            printf("Highwings %d %s %d\t is\t Lowwings %d %d %s\n", 
                    highwing_year, highwing_month_name, highwing_day - 1,
                    lowwing_year, lowwing_month + 1, 
                    lowwing_day_names[lowwing_day]);
            
            /* Reset all the values which won't be re-assigned from stdin. */
            unify_day = 0;
        }
    }

    return EXIT_SUCCESS;
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://luxing.im/a5p1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">31</post-id>	</item>
	</channel>
</rss>
