Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Someone with c++ knowledge please help

Name: Anonymous 2011-03-09 0:46

Im using visual c++ 2008 express edition from microsoft

Write a program that reads in 16 values from the keyboard and tests whether they form a magic square when put into a 4x4 array. You need to rest two features :

-does each of the numbers 1,2,...,16 occur in the user input
-When the numbers are put into a square, are the sums of the rows, columns, and diagonals equal to eachother?

a magic square is when the sum of the elements in each row, column and in the two diagonals have the same value.

Name: Anonymous 2011-03-09 15:57

C version


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

#define FALSE 0
#define TRUE 1

typedef int magic_square[16];

/* The magic sum is given by n * (n^2 + 1) / 2, n the order of magic square */
#define MAGIC_SUM 34

static int lines[10][4] = {
    /* Rows */
    {  0,  1,  2,  3 },
    {  4,  5,  6,  7 },
    {  8,  9, 10, 11 },
    { 12, 13, 14, 15 },
    /* Columns */
    {  0,  4,  8, 12 },
    {  1,  5,  9, 13 },
    {  2,  6, 10, 14 },
    {  3,  7, 11, 15 },
    /* Diagonals */
    {  0,  5, 10, 15 },
    {  3,  6,  9, 12 }
};

int is_valid_magic_square(magic_square ms)
{
    unsigned short bitmap;
    int sum;
    int i, j;

    for (i = 0; i < 16; i++)
    {
        if (ms[i] < 1 || ms[i] > 16)
            return FALSE;
        bitmap |= 1 << (ms[i] - 1);
    }

    if ((bitmap & 0xFFFF) != 0xFFFF) /* Have 1-16 */
        return FALSE;

    for (i = 0; i < 10; i++)
    {
        sum = 0;
        for (j = 0; j < 4; j++)
            sum += ms[lines[i][j]];
        if (sum != MAGIC_SUM)
            return FALSE;
    }

    return TRUE;
}

int main(int argc, const char * const *argv)
{
    magic_square ms;
    int i;
    int x;
    int ret;

    printf("Enter 16 numbers>\n");
    fflush(stdout);

    i = 0;
    while (i < 16)
    {
        ret = scanf("%d", &x);
        if (ret == 1)
            ms[i++] = x;
        if (ret == EOF)
        {
            perror(argv[0]);
            abort();
        }
    }

    if (is_valid_magic_square(ms))
        printf("Valid!\n");
    else
        printf("Invalid!\n");

    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List