# Atom Square

A magic square is a square grid of numbers, arranged so that the sum of the numbers in any horizontal, vertical, or diagonal line is the same.

As a magician, you can use a magic square as a form of mentalism or a mathematical magic trick. You can ask a spectator to choose any number on the grid, and then reveal the sum of the numbers in any row, column, or diagonal that contains that number. You can also ask the spectator to choose a row, column, or diagonal and then reveal the sum of the numbers in that line.

This mini-app is helping you to make a magic square based on a number. You just have to enter the number the spectator said and copy the numbers appearing on the PeekSmith 3 screen.

``````const PEEKSMITH_ID = '*';

// the array will contain the numbers of the 4x4 square
let square = newUint8Array(16);

function main() {
ps.connect(PEEKSMITH_ID);
ps.print('AtomSquare');
}

function formatNumber(n) {
if (n < 10) return `\xA0\${n}`;
return `\${n}`;
}

function buildSquare(n) {
// we can calculate a magic square for numbers
// between 22 and 117 when we would like to end with
// max. two digit positive numbers
if (n < 22 || n > 117) {
ps.print(`<\${n}>\nINVALID`);
return;
}
square = 7;
square = 12;
square = 1;
square = n - 20;
square = 2;
square = n - 21;
square = 8;
square = 11;
square = n - 18;
square = 3;
square= 10;
square= 5;
square= 9;
square= 6;
square= n - 19;
square= 4;
let result = '';
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
result += formatNumber(square[row * 4 + col]);
result += col < 3 ? ' ' : '\n';
}
}
ps.print(result);
}

let num = '';
let mapping = [
'1', '2', '3',
'4', '5', '6',
'7', '8', '9',
's', '0', '<'
];
function calc() {
if (num === '') return;
clearTimeout(timer);
buildSquare(parseInt(num));
num = '';
}
let timer;
function type(buttonId) {
let digit = mapping[buttonId];
if (digit === 's') return calc();
if (digit === '<') {
if (strLen(num) > 0) num = strSub(num, 0, strLen(num) - 1);
} else {
num += digit;
}
clearTimeout(timer);
timer = setTimeout(calc, 2000);
ps.print(`<\${num}>`);
}

function onEvent(e) {
if (e.type === 'click' && e.source === 'atom:button') type(parseInt(e.value));
}``````