Magic Square programming question

Recommended Posts

First I'm not asking for the answer, this isn't a homework assignment or something.

I have this programming test thing tomorrow for a potential job, as an entry php developer.

I looked up "entry level program test for job" and I came across a thread and a guy was saying that he was asked these three questions, first one is regarding the magic square. I didn't know what that is, read about it... side note, in a Java class I took we created a four-square game so I imagine the principle is the same, but I would like to solve it with php but any way.

I'm not sure about the question quoted here:

1. Write a function that given a two-dimensional array [x, x] checks if it is a magic square and returns true or false. A square is magic when the sum of all the numbers in each of the sequences vertically, horizontally and diagonally is the same. http://mathworld.wolfram.com/MagicSquare.html

I am initally inclined to say I can throw out non-square two-dimensional arrays right? Since for the diagonal test, the length has to be the same as the height/width of the square? From a graphic found on the link in that quote, the diagnoal test was only one diagnoal although probably rotated 90 degrees to check the other direction.

The other question was that the associated values of the indexes of each array is arbitrary right? So when I test this function myself, I would have to set the values to a known-magic square? I get that the idea is to enter arbitrary values into each arrary "coordinate?" what do you call that? Dimension...

So a 2D array of [2,2] could have for x, x0 = 1, x1 = 1 and y, y0 = 1, y1 = 1, that would work... but for example if x0 = 2 and y1 = 5 then it wouldnt' work... so... probably a bad sign that I'm having this much difficulty solving this or thinking too much about it and not just solving, at any rate it is a good review.

The job is for entry level, pays at 35K a year, which is a step up for me. Would be pretty happy to get this job.

I've been working with php for about a year and there seems to be concern for Object Oriented Programming and Model View Controller... I believe the purpose of the test is to see how you think and solve problems, but actually solving the problem would be nice.

Share on other sites

I believe the purpose of the test is to see how you think and solve problems

That is correct. In most cases they're not looking for a complete solution. They just want to get a feel for how you approach problems, what you struggle with, if you're interested/passionate, etc.

Share on other sites

Yeah I don't know why I'm having trouble wrapping my head around this...

Say there is a simple 2 x 2 array, with values for x, 1, 1 and y, 1, 1 this works.

So when I iterate for a horizontal test, how do I arbitrarily identify the key-value pair?

As in, [2,2]

1,0 = 1

2,0 = 1

1+1 = 2

1,1 = 1

2,2 = 1

1+1 = 2

the foreach loop uses

```foreach (\$arr as \$value) {

}```

I'm going to work on this for a bit, this seems so simple I just have to translate to php

Actually, I will use this "Lo Shu" magic square as my reference to test if my function works as I know the values for that and it is 3,3 versus 2,2.

Oh wait... yeah, this is still two dimensional, doesn't have depth

Already lost, starts at 0, so 3x3 is [2,2] right? ehh... not looking good

side note: It's not the money that I'm really after. This would be my first actual job related to web development which I could build upon for future jobs. "Gets my foot in the door" so to speak.

Edited by greenace92
Share on other sites

Well I had to brush up on arrays, have never actually used them but knew of them in my applications...

I did solve this one here called "Fizz Buzz" PHP is a "scripting" language right? But I feel like I can program with it... is there a difference aside from not comparing to C for example for memory and cpu... lower level

See right here, perfect example of this "You think you know more than you do."

There was this php test that pretty much told you that you were an idiot when not guessing correctly how many questions you got wrong. It was also outdated too I realized as I solved each problem.

But I agree though I fall in that category of "knows some, not really sure what he's doing."

"Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”."

This is what I wrote

```<?php

for (\$i = 1; \$i <= 100 ; \$i++) {

if(((\$i % 3)==0) && ((\$i % 5)==0)){

echo "#".\$i." "."Fizz Buzz".'<br>';

}else if(\$i % 3 == 0){

echo "#".\$i." "."Fizz".'<br>';

}else if(\$i % 5 == 0){

echo "#".\$i." "."Buzz".'<br>';

}else {
echo "#".\$i.'<br>';
}

}

?>```

Output is crazy long

#1
#2
#3 Fizz
#4
#5 Buzz
#6 Fizz
#7
#8
#9 Fizz
#10 Buzz
#11
#12 Fizz
#13
#14
#15 Fizz Buzz
#16
#17
#18 Fizz
#19
#20 Buzz
#21 Fizz
#22
#23
#24 Fizz
#25 Buzz
#26
#27 Fizz
#28
#29
#30 Fizz Buzz
#31
#32
#33 Fizz
#34
#35 Buzz
#36 Fizz
#37
#38
#39 Fizz
#40 Buzz
#41
#42 Fizz
#43
#44
#45 Fizz Buzz
#46
#47
#48 Fizz
#49
#50 Buzz
#51 Fizz
#52
#53
#54 Fizz
#55 Buzz
#56
#57 Fizz
#58
#59
#60 Fizz Buzz
#61
#62
#63 Fizz
#64
#65 Buzz
#66 Fizz
#67
#68
#69 Fizz
#70 Buzz
#71
#72 Fizz
#73
#74
#75 Fizz Buzz
#76
#77
#78 Fizz
#79
#80 Buzz
#81 Fizz
#82
#83
#84 Fizz
#85 Buzz
#86
#87 Fizz
#88
#89
#90 Fizz Buzz
#91
#92
#93 Fizz
#94
#95 Buzz
#96 Fizz
#97
#98
#99 Fizz
#100 Buzz

Edited by Zane
Share on other sites

Don't worry so much.

A lot of those tests are supposed to weed out complete morons who cannot write any code at all. Since you clearly don't fall into that category, there's nothing to be afraid of. Even if you do make a mistake somewhere or need a bit longer, it's obvious that you can program.

So don't waste your time with stuff like “Fizz Buzz”.

Share on other sites

Just showing your employer that you care this much to get it right will say a lot all on its own.

Share on other sites

You'd be surprised how many people applying for programming jobs cannot write the Fizz Buzz code.

People get their feet wet in PHP or some other "seemingly friendly" language and suddenly they are confident enough to go out and start applying for professional developer positions.

If it were really that easy, we would all be earning minimum wage and having to bag burgers and fries in between designing, coding, testing and debugging.

Share on other sites

I just took the test... wow

I learned a lot though, from this brief exercise in life.

I always had this thought of "I'm going to run away to California and everything will be great!"

Standing there waiting for a cab, I reliazed how I take my data entry job for granted and taking the bus and life... well basically I feel domesticated.

The test was alright although I can't say that I answered everything 100%.

They gave me the option to choose from programming languages, PHP was an option and the job is for PHP developing.

I couldn't remember the SQL queries verbatum but I wrote them as best as I could...

Sadly I was not able to write three inherent principles of Object Oriented Programming... I said that objects are created from classes, children inherit properties from parents, variables to properties, functions to methods... efficient coding due to less code

I don't know haha, I didn't do that great I mean... there was a question about opening a sample.txt file and I only ever did that with C++ through command line like 3 years ago, and perhaps I did it with PHP for like a day but could not remember.

I do feel dumb haha.

How can you tell if a database is empty? haha I was like "Look at PHPMyAdmin?" Query the row see if there is a result.

There was question on iterating through an array without built-in-array function.

I used a for loop and the \$i as the counter...

There was something as simple as take 99-999999 and for any given value, replace the first 99, with the letters of the abc ranging from 01 to 26...

I could not recall the exact way to use explode but I was like "separate by the - and then run a loop through an array to compare 01 to 26 to the two characters"

at any rate... it was an interesting experience, I haven't taken a programmer competency test (as it was called)

Thanks for the replies and supportive words.

I will still be working on my own stuff regardless of being hired but I also learned how unprepared I am for life.

Recruiter: "Do you have a reliable form of transportation?"

Me: "Uhh... yeah... bus, bicyle...."

Recruiter: "You sort of broke up there, what did you say?"

Me: "No car".

I've been taking for granted that I spend \$64.00 a month for transportation that   returns a range of \$1,600.00 to \$2,400.00 a month. I used to have a car that cost me at least \$116.00 a month plus gas.

At any rate... thanks

I apologize if the material I added to this forum is irrelevant.

I spent \$70.00 or more on this "potential interview" I get that it could result in a new job which pays more than my current job... it was so stupid of me... I wrote this instructions because I thought "I don't need to pay for a data plan, I have WiFi all the time." I got lost, had to hire a taxi to take me, then pick up my bike and go home... ahh life

Edited by greenace92
Share on other sites

Writing a lot, I apologize.

I do want to thank this forum and the members that make up phpfreaks(forums) I've learned a lot here. I've learned a lot from other sites as well.

Share on other sites

Don't sweat it man. Do research on all of the things that you struggled with or didn't know. This is how we grow.

Interview questions are largely bullshit anyway. They're more about memorization and pointless trivia than they are actual coding ability.

Share on other sites

Here are the answers for reference:

three inherent principles of Object Oriented Programming

There are 4 in total:

1. Abstraction

2. Inheritance

3. Polymorphism

4. Encapsulation

How can you tell if a database is empty?

```USE database_name;
SHOW TABLES;```
Share on other sites

It's pretty sad to think that I've worked on this magic square for several hours over the course of three days. With sleep deprivation mind you.

I realize that this is super long. I don't know how the "Magic Square" would be given to me, but in this scenario I simply included an existing magic square. Side note, I realized this is what Sudoko is right? Crazy...

Anyway, I also realize that I could have done this much shorter, like any iteration of the same function where I incremented the \$i value or any value by 1, I could have passed a function argument variable or list, and incremented that by one when calling the function. I tried that, I'm not sure why this doesn't work:

```<?php

function rowSum(\$inc_row) {

\$GLOBALS['vertical_sum'] = 0;

\$vsum = \$GLOBALS['vertical_sum'];

for(\$i=0; \$i<=2; \$i++){

\$convert = (int)\$string_parts[\$i+\$inc_row];

\$vsum = \$vsum+\$convert;

return \$vsum;

echo \$vsum;

}

}

rowSum(0);

?>```

At any rate, this is what I created that does work, this is a perfect example of "blunt-force engineering" just a random term I thought of a while ago where I kept trying by smashing things together without actually figuring out what was wrong until it worked. Lost a lot of RC parts that way...

Yeah I'm really going about this the dumb way, there are several things that I could easily get rid of by "smart coding" eg. coding efficiency.

For example, comparing every value, I realize that it works off the function n(n-1) where n is the number of things being compared to each other.

So 8 variant rows being compared is 8*7 = 56 comparisons = dumb

Wait I think I found a solution (writing into response page while trying to finish code)

This doesn't work, but I found out about in_array

```<?PHP

\$a = 2;
\$b = 3;
\$c = 4;
\$d = 5;

if(\$a!=\$b!=\$c!=\$d){
echo "not equal";
}else{
echo "comparison failed";
}

?>```

Actually I don't think this in_array will work

"Transitive relation"

I'm not sure if it is testing from left to right or if all have to be true in order to pass... as in the outer left most compares to the outer right most.

Ahh man... it just occurred to me this test is not scalable to different size 2D arrays... it's only designed for 3x3 and not even 2x2.

Wow... alright have to learn how to make perhaps even a single row iterating function, and a single summing function to do this and have it scale to whatever input. This is only designed for one array size.

Funny you can't even tell what is going on when you run it, it just says "This 2D array is a magical square"

```<?PHP

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

// build sample array

\$array = array();

// bottom row

\$array[0][0] = 8;
\$array[1][0] = 1;
\$array[2][0] = 6;

// middle row

\$array[0][1] = 3;
\$array[1][1] = 5;
\$array[2][1] = 7;

// top row

\$array[0][2] = 4;
\$array[1][2] = 9;
\$array[2][2] = 2;

// access array and store into string to be split

\$GLOBALS['value-chain'] = "";

foreach (\$array as \$x) {

foreach (\$x as \$y) {

\$GLOBALS['value-chain'] = \$GLOBALS['value-chain'].\$y;

\$short = \$GLOBALS['value-chain'];

}

}

// perform preliminary test of diagonal direction-up and down sum,
// one vertical row, and one horizontal row,
// if pass continue to full test

// change order of string

// first three horizontal, could sum while I'm at it

\$horizontal_string = "";

\$string_parts = str_split(\$short);

\$new_i = 0;

for (\$i=0; \$i<=2; \$i++) {

if(\$i!=0){

\$new_i = \$new_i+3;

\$horizontal_string = \$horizontal_string.\$string_parts[\$new_i];

}else {

\$horizontal_string = \$horizontal_string.\$string_parts[\$i];

}

}

// second three horizontal

\$new_i_2 = 1;

for (\$i=1; \$i<=3; \$i++) {

if(\$i!=1){

\$new_i_2 = \$new_i_2+3;

\$horizontal_string = \$horizontal_string.\$string_parts[\$new_i_2];

}else {

\$horizontal_string = \$horizontal_string.\$string_parts[\$i];

}

}

// last three horizontal

\$new_i_3 = 2;

for (\$i=2; \$i<=4; \$i++) {

if(\$i!=2){

\$new_i_3 = \$new_i_3+3;

\$horizontal_string = \$horizontal_string.\$string_parts[\$new_i_3];

}else {

\$horizontal_string = \$horizontal_string.\$string_parts[\$i];

}

}

// horizontal string now exists

// echo '<br>'.'horizontal string'.\$horizontal_string;

// diagonal up-direction

\$string_parts_h = str_split(\$horizontal_string);

\$dsumu = ((int)\$string_parts_h[0])+((int)\$string_parts_h[4])+((int)\$string_parts_h[8]);

// diagonal down-direction

\$dsumd = ((int)\$string_parts_h[6])+((int)\$string_parts_h[4])+((int)\$string_parts_h[2]);

// compare

if((\$dsumu != \$dsumd)){
echo "Not a magical square";
}

// continue to vertical test

// vertical sum left

\$string_parts = str_split(\$short);

\$GLOBALS['vertical_sum_1'] = 0;

\$vsum1 = \$GLOBALS['vertical_sum_1'];

for(\$i=0; \$i<=2; \$i++){

\$convert = (int)\$string_parts[\$i];

\$vsum1 = \$vsum1+\$convert;

}

// echo '<br>'.'<br>'.\$vsum1;

// compare 2

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1)){
echo "Not a magical square";
}

// continue to horizontal test

// sum horizontal bottom

\$string_parts_h = str_split(\$horizontal_string);

\$GLOBALS['horizontal_sum_1'] = 0;

\$hsum1 = \$GLOBALS['horizontal_sum_1'];

for(\$i=0; \$i<=2; \$i++){

\$convert_h1 = (int)\$string_parts_h[\$i];

\$hsum1 = \$hsum1+\$convert_h1;

}
// echo '<br>'.'this is horizontal sum '.' '.\$hsum1;

// compare 3

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1) && (\$vsum1 != \$hsum1)){
echo "Not a magical square";
}

// full test

// rest of vertical

// vertical sum middle

\$GLOBALS['vertical_sum_2'] = 0;

\$vsum2 = \$GLOBALS['vertical_sum_2'];

for(\$i=0; \$i<=2; \$i++){

\$convert2 = (int)\$string_parts[\$i+3]; // +3 shifts string array position

\$vsum2 = \$vsum2+\$convert2;

}

// compare 4

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1) && (\$vsum1 != \$hsum1) && (\$hsum1 != \$vsum2)){
echo "Not a magical square";
}

// vertical sum right

\$GLOBALS['vertical_sum_3'] = 0;

\$vsum3 = \$GLOBALS['vertical_sum_3'];

for(\$i=0; \$i<=2; \$i++){

\$convert3 = (int)\$string_parts[\$i+6]; // +6 shifts string array position

\$vsum3 = \$vsum3+\$convert3;

}

// compare 5

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1) && (\$vsum1 != \$hsum1) && (\$hsum1 != \$vsum2) && (\$vsum2 != \$vsum3)){
echo "Not a magical square";
}

// rest of horizontal

// sum horizontal middle

\$GLOBALS['horizontal_sum_2'] = 0;

\$hsum2 = \$GLOBALS['horizontal_sum_2'];

for(\$i=0; \$i<=2; \$i++){

\$convert_h2 = (int)\$string_parts_h[\$i+3]; // +3 shifts string array position

\$hsum2 = \$hsum2+\$convert_h2;

}

// compare 6

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1) && (\$vsum1 != \$hsum1) && (\$hsum1 != \$vsum2) && (\$vsum2 != \$vsum3) && (\$vsum3 != \$hsum2)){
echo "Not a magical square";
}

// sum horizontal top

\$GLOBALS['horizontal_sum_3'] = 0;

\$hsum3 = \$GLOBALS['horizontal_sum_3'];

for(\$i=0; \$i<=2; \$i++){

\$convert_h3 = (int)\$string_parts_h[\$i+6]; // +6 shifts string array position

\$hsum3 = \$hsum3+\$convert_h3;

}

// compare 7

if((\$dsumu != \$dsumd) && (\$dsumd != \$vsum1) && (\$vsum1 != \$hsum1) && (\$hsum1 != \$vsum2) && (\$vsum2 != \$vsum3) && (\$vsum3 != \$hsum3)){
echo "Not a magical square";
}else {
echo "This 2D array is a magical square";
}

?>
```
Share on other sites

This is probably a problem, I changed the first array value from 8 to 3, and the output was

Not a magical square not a magical square this 2D array is a magical array

The last one that compares everything should not have passed so resulting in "...is a magical square"... ahhh

Yeap... if one passes, they all pass oh...

I guess I just had to change the && to ||

Well, this is my stab at this for now...

Have to improve by using significantly less code and scalability

Edited by greenace92
Share on other sites

Just for fun, this was my attempt

```\$square = [ [ 4, 9, 2],
[ 3, 5, 7],
[ 8, 1, 6] ];

\$rowtots = [];
\$coltots = [];
\$k=count(\$square);

// ROW and COL TOTALS
for (\$r=0; \$r<\$k; \$r++) {
for (\$c=0; \$c<\$k; \$c++) {
if (isset(\$rowtots[\$r]))
\$rowtots[\$r] += \$square[\$r][\$c];
else
\$rowtots[\$r] = \$square[\$r][\$c];

if (isset(\$coltots[\$c]))
\$coltots[\$c] += \$square[\$r][\$c];
else
\$coltots[\$c] = \$square[\$r][\$c];

}
}
// put the totals into a sing;e array for later checking
\$totals = array_merge(\$rowtots, \$coltots);

// DIAGONALS TOTALS
\$diag1 = 0;
for (\$r=0, \$c=0; \$r<\$k; \$r++, \$c++) {
\$diag1 += \$square[\$r][\$c];
}
\$totals[] = \$diag1;  // append to array

\$diag2 = 0;
for (\$r=0, \$c=\$k-1; \$r<\$k; \$r++, \$c--) {
\$diag2 += \$square[\$r][\$c];
}
\$totals[] = \$diag2;  // append to array

//  output square and result
foreach (\$square as \$row) {
echo '|'.join('|', \$row).'|<br>';
}
echo count(array_count_values(\$totals))==1 ? 'Magic square' : 'Not a magic square';
```
Share on other sites

wow 44 lines haha

beats the hell out of 276 haha

I like your matrix notation ? Or array notation? not sure

not looking at your solution till I condense mine but thanks for your input, shows me how much smaller the code can/should be.

Curious if it is scalable?

Again, I'm not sure how the values would be entered with varying dimensions... unless they had a bunch of them lying around and fed it into the input...

Edited by greenace92
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.