Programming Problem #2 - Magic Squares (Novice/Intermediate)

Tech With Tim · Intermediate ·🛠️ AI Tools & Apps ·8y ago

Key Takeaways

The video solves the Magic Squares programming problem using 2D arrays and matrices, checking rows, columns, and diagonals for sum, and provides a step-by-step approach to determine if a given matrix is a Magic Square or not, utilizing tools such as enumerate, matrix, for loop, range, and list, and applying concepts like magic squares, matrix operations, data analysis, and input validation.

Full Transcript

hey guys and welcome back to the second video in my programming problem-solving series and in today's video we're moving into a bit more of a complex problem so the last video I did we had a decent problem it wasn't too hard it wasn't too difficult is fairly straightforward and fairly simple if you guys are new to programming and you're new to solving problems I'd recommend you go watch that one first I'll leave a card up in the top right hand corner and I kind of give a little intro and go over what the series is about if you're wondering about that so let's just get right into this problem today this one is called magic squares now pretty much what this is is we all just read it out to you the introduction of magic squares a 2d matrix composed of n to the power of 2 or n squared integers where n is the length of one row or one column and in a Magic Square each row each column and two and the two diagonals must sum to the same value so we'll look at the example below here and you can see we have a square we have two nine four seven five three six one eight and all of them some to 15 so the diagonals here and so they'll sum to 15 so how can we figure out if a square is a Magic Square and that's what the problem says here so it says given a 2d matrix which is the same thing as this right here in the same form as shown and as mentioned above your program must determine if the square is magic or not magic it will output magic or not magic accordingly so your program will first take an input n representing the length of one row of the matrix it will then take n lines with input containing n integers separated by spaces and then if we look below I have my sample input and output that I've written here for you guys obviously this first one is pretty straightforward just to show you the obvious Nastase if all of the numbers are the same then obviously the square is going to be magic because no matter where you add where you sum all the things they're all going to equal four so what am i saying six in this case and you can see if you didn't quite understand input line here what's first gonna happen is your program is gonna take one line here which is gonna tell you how long one row is and how many rows there are so it tells you three three rows and then in each row you have three elements right so this next one is a more complex case you can see we have a length of four so this square is indeed magic it might not look like it and it's hard to tell and that's why we write programs to determine this so when you guys are testing out your program make sure you test out different all these different test cases so I have these two that are magic I also have another one here that's not magic I just made these numbers up and wrote them in here so if you guys just make up your own numbers and type them in then you can also test if those are not magic squares so yeah I'll give me a second here to pause the video if you guys want the actual sheet here that I have then I have actually shared a Google tribe with you in the description down below I forgot to mention this in my last video but if you go to the description it'll say my solutions or my answers or whatever click on the link there it should bring you to a Google Drive and then on that Google Drive you can see the the folder I have go to the according problem so it'll say magic squares and then you'll be able to see this and my python file is with the solution as well so I'll scroll through it here so you guys can have a look pause the video when you feel like it and go ahead and try the problem again this is slightly more advanced so I'd say this is probably about a novice problem and it should take you about 15 to 20 minutes to complete may be a bit long okay so I hope you guys have had a chance now to complete the the program hopefully you were able to get it working if you've noticed it's not too difficult to actually code this it just is slightly tedious and it takes a few steps so let's get into the solution now okay so the solution so I have already here in Python my solution so the first part of the problem is understanding how it works so this one wasn't too complicated we have a square and we just have to figure out all the numbers do they add to the same thing so the first part actually after we figure out so I guess the second part is now taking the input and you'll notice as I introduce more problems the input for them is gonna become a little slightly more complex and even just taking the input for the Perl is going to be something that you have to figure out yourself so here we said n is equal to the int of input so I'll just show you when I run the program all I have here I don't have any prompts it just all you do is you type a number and then you're prompted to type the next row of numbers accordingly like so I'm and yeah and then it will output whatever they obviously that didn't work so I didn't type the right amount anyways we then set up a new array where I guess the list in Python I'm calling this a matrix and then I'm saying four rows in range n so we take however many rows or is gonna be and then for all those rows were then gonna take all those numbers on each line so we say nums are equal to that input of that line again this can happen say if we had four rows this will happen four times and then we append all those numbers into a list into a two-dimensional list so we actually end up having a matrix of matrix that looks something like this and it has a bunch of lists inside of it and that's called a two-dimensional array or two-dimensional list and that's the way that I like to set up the problem just so that I can kind of visualize it as well and that's each one of these would represent one one row so if we had one one one one one one one one one this would be a Magic Square with three rows and three elements in each row all right so three columns and you can see that if we were add all these together then we would get three for all of them and it would all work out like that okay so I'm gonna get rid of this now but that was just an example to show you so that's what that that's what this line is doing here it's just pretty much setting it up into a two-dimensional array and then I've just written a comment here saying we can take a three step approach so there are three things that the square has to satisfy right so the rows must add to each other the columns must add to each other and the diagonals must add as well so let's check all three of those things individually you can do them all in one big step but I prefer just to do them individually it keeps the program cleaner and it's easier to read especially for you guys so I first just start off by setting a variable called magic now what this is going to do is we're just gonna set this to false the second we find that the square is no is no longer magic because once we find that it's not magic there's no point in continuing we can just set it to false right away so now what I'm doing here is I'm creating a new matrix and this is called C matrix so this might seem a little confusing at this point but pretty much we have a two dimensional list up here which I'm calling matrix that has all of our rows and columns it looks exactly like this if you were to print it out onto the screen that's what it would look like your Magic Square and then here I'm setting up a column matrix now what I'm doing is I'm just adding a new level into the array a new dimension into the list according how many rows we have how many columns we have and then after this I'm just grabbing the value that we want to check so because we know that all of the columns and all the rows need to add up to the same value we can just pick any column any row that we want and just get the sum of it and say well we need to make sure that everything equals that value so that's why I've just picked to the sum of matrix 0 so this is Rho 0 that's the sum of it and then we start by checking the rows so here I have a new for loop say for X row in enumerate matrix if you don't know what enumerate does it pretty much allows you to have a counter variable and a variable that has the actual value in the matrix so it's really useful to use that so we say if the sum of our row which is going to be equal to obviously the row it is not equal to value which is 1 we've checked up here then we're just gonna instantly say magic equal to false that's it we're done we don't need to do anything else and we know the square is no longer a magic so we check all of the rows now say that they are they do all add to the same thing well now what we need to end up to do is we need to set up our column matrix so the first matrix I set up has the rows in it now we want ones with the columns in it so that we're able to add all of the columns up together so we're going across adding not and now we want to add down so I just do this in the same step as I'm checking the rows because it makes sense to do it in the same for loop rather than setting up a new one again I'm saying for a common element in a numerate row so for every element in our row I'm going to add that element into the corresponding matrix for the column so into so for each row I'm gonna have a different dimension that each element goes into so for example this is this one if we're on zero zero right now we're gonna go into the first first column and this is the first element in the first column and then we continue on and then the second element well that's gonna be in the second column the third element in the row that's gonna be in the third column and then once we go down to the second row so now we're on row two then we put this this is the second element in the first column and so on and so forth okay so now that we've set up our column matrix we go ahead and we can check our columns so now that we have them we can do the exact same thing we did up here except instead of using rows we're using columns and we're using the other matrix and we're just gonna say well if these columns if they don't sum up to the value that we've set at the beginning here then we know it's not magic so we'll set magic equal to false okay so this that part was fairly straightforward I know I went kind of fast through it but what we do here now is a little more complicated and this is with diagonals so I'm just setting up two variables to start here I and J now I equals zero Jake this is gonna correspond this is row and this is column okay so I've just set up now a little diagonal two-dimensional list as well and this is gonna have the diagonal on the left side and the diagonal on the right side and the reason I can do this rather than having to set it up variable wise like I have up here is because I know that no matter how big the square is we're only gonna have two diagonals corner to corner so it's fine to do it like this now I'm saying for X in range and so for the amount of elements or the amount of rows so on we're gonna say a diagonal zeros to the left side and we're gonna add matrix I and matrix J now what this does is since we're starting at 0 0 it's gonna add 0 0 and I'm just gonna pull up this actually because it's gonna make it a bit easier to understand so we're gonna have 0 0 here which gonna be 2 and and from the right side we're gonna say n minus 1 minus I now what this does is it we're on the same row so if I get back here we're on the same rail we're still here in the same Jake J value but we need to go we need to go back because right now we're here we want to get to 6 so how do we do that the way we do that is we say well we know that there's 3 elements in here if we're currently at 0 then we need to first subtract 1 because obviously there's not a third what do you call them here it's only it only goes up to 2 if we're counting like programmers which we are so we say n minus 1 now we're at 2 & 2 minus I since I zero that plops this over to here where 6 is so we can get the other diagonal value now after we do that we're gonna add 1 to both of these values so you can see that over here we add 1 to both of them so that means we're now moving down and we're moving to the right so I've started at 0 0 I'm now going down 1 to the right where I get 5 and same thing from this side I'm here starting at that so now that our values gone up by 1 and we've subtracted 1 from it mine is from a done or whatever and now we're back in the middle as well and then we moved down one more time so for here we move down and then we move to the right for this one here and then here we're moving to the left so we're moving down or moving to the left so we can get that value and we just stored them in this diagonals two-dimensional list here and then we're just checking with a simple if statement here if diagonal 0 does not equal value or the sum of diagonals 1 does not equal value magic equals false and finally the conclusion if magic after all of this checking still equals true we haven't found any contradictions in the sums then we print magic otherwise we print not magic and yes that is my solution now I know this is a little little bit harder but these are good problems to start thinking about this one is just more tedious than it is difficult and in the next video we're gonna get into one that's maybe not as long but it's gonna require a bit more thinking so I'm gonna go ahead and run my program now prove to you guys that it does indeed work so first we'll start with the very basic case like that tu-tu-tu-tu-tu-tu like that we get a magic square run the program again I'm gonna put some random numbers in here this time dude 3 4 5 3 2 4 5 3 4 5 not magic now if I pull up my output here this 4 1 the one that you guys should be checking as well pull it up again how can I get this oh it's on the screen and I have to push it all the way over okay and let's make this a bit smaller there we are I'm gonna start by typing 4 and then 60 1 2 3 13 5 11 10 8 9 7 6 12 and 4 14 15 1 and we get magic so we can confirm that this program is indeed working and if you guys again have any other better way of doing this you found a more efficient solution make sure you either send me a link in the comments below or just post your code down there I'll have a look at it and if it is indeed faster than mine that I'll be sure to show you guys out in the next video so that's been it for this video if you guys enjoyed please make sure you leave a like on the video and subscribe to the channel and make sure you're around every Thursday for new programming problems [Music]

Original Description

Programming Problems & Solutions #2! In this weeks problem I will be showing a novice/intermediate problem called Magic Squares. This is a fairly popular problem in computer science and programming. There are many different solutions to this but only a few are efficient. I will be walking you through my solution step by step and focusing on matrixes/2d arrays/2d lists as these are the key to solving problems like this one. Think you have a better solution than me? Leave a comment down below with it or a link to it and I will be sure to check it out and shout you out in my next video! My Solutions: https://goo.gl/eKWNzR Want To Support This Channel? Bitcoin: 1PbkAYLFaJBgjbKn2ptGyBz65xWN8hJgBU Ethereum: 0xdd42dbbdba60f7163fc7a840e189474b6e8bfcad Ripple: rD4arM9CVjQWqi8f1kxdpCgkCgEkqBgtud Please leave a LIKE and SUBSCRIBE for more content! Tags: - Tech - Tech With Tim - Crypto - Programming - Coding - Pygame - Python Tutorials - Solving Problems - Coding Problems - Think like a computer scientest - Programming Problems for Begginers - Programming Problems and Solutions - Programming Problems - Train your brain
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video teaches how to solve the Magic Squares programming problem by checking rows, columns, and diagonals for sum, and provides a step-by-step approach to determine if a given matrix is a Magic Square or not. The problem is solved using 2D arrays and matrices, and applies concepts like magic squares, matrix operations, data analysis, and input validation. The video is suitable for novice/intermediate level programmers.

Key Takeaways
  1. Take an input n representing the length of one row of the matrix
  2. Take n lines with input containing n integers separated by spaces
  3. Set up a 2D array to represent the Magic Square
  4. Check if the rows add up to the same number
  5. Check if the columns add up to the same number
  6. Check if the diagonals add up to the same number
  7. Add new dimension to array
  8. Create column matrix
  9. Check diagonals for sum
💡 The Magic Squares problem can be solved efficiently by using a 2D array to represent the matrix and checking the sums of rows, columns, and diagonals

Related Reads

📰
I built a free ATS resume checker that runs entirely in your browser - here's how
Learn how to build a free ATS resume checker that runs in your browser, helping job seekers increase their chances of getting noticed by recruiters
Dev.to · Dipesh Gyawali
📰
3 Free AI Tools I Use to Save Hours Every Week
Discover 3 free AI tools to automate repetitive tasks and save hours every week, boosting productivity
Dev.to · Hari Haran
📰
My AI Bill Dropped 95% When I Switched to Chinese Models
Switching to Chinese AI models can significantly reduce costs, with one company experiencing a 95% drop in their AI bill, making it a viable option for businesses looking to cut expenses.
Dev.to AI
📰
AI Dubbing for Short Drama: The 2026 Playbook That Actually Scales
Learn how to scale AI dubbing for short drama with the 2026 playbook, improving efficiency and quality in audio post-production
Dev.to AI
Up next
Presentation Conversion Made Secure for Lawyers with LawWiz
LawWiz
Watch →