Last active
October 6, 2024 15:10
-
-
Save mshafiee/64a5d660c079cca29e06dd8552be7360 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Magic Square Generator</title> | |
<style> | |
table { | |
border-collapse: collapse; | |
margin: 20px 0; | |
} | |
table, th, td { | |
border: 1px solid black; | |
} | |
th, td { | |
padding: 10px; | |
text-align: center; | |
} | |
.highlight { | |
background-color: yellow; | |
} | |
.index { | |
color: red; | |
font-size: smaller; | |
vertical-align: super; | |
} | |
</style> | |
</head> | |
<body> | |
<h1 id="title">Magic Square Generator</h1> | |
<label for="languageSelect">Select Language:</label> | |
<select id="languageSelect" onchange="setLanguage()"> | |
<option value="en">English</option> | |
<option value="fa">فارسی (Persian)</option> | |
</select> | |
<br><br> | |
<label id="labelMagicalNumber" for="magicalNumber">Enter magical number:</label> | |
<input type="number" id="magicalNumber" required> | |
<br> | |
<label id="labelOrderType" for="orderType">Enter order type:</label> | |
<input type="radio" id="water" name="orderType" value="water"> | |
<label id="labelWater" for="water">Water</label> | |
<input type="radio" id="fire" name="orderType" value="fire"> | |
<label id="labelFire" for="fire">Fire</label> | |
<input type="radio" id="air" name="orderType" value="air"> | |
<label id="labelAir" for="air">Air</label> | |
<input type="radio" id="earth" name="orderType" value="earth"> | |
<label id="labelEarth" for="earth">Earth</label> | |
<br> | |
<button id="generateButton" onclick="generateMagicSquare()">Generate</button> | |
<button id="clearButton" onclick="clearResults()">Clear</button> | |
<div id="result"></div> | |
<script> | |
const translations = { | |
en: { | |
title: 'Magic Square Generator', | |
labelMagicalNumber: 'Enter magical number:', | |
labelOrderType: 'Enter order type:', | |
labelFire: 'Fire', | |
labelEarth: 'Earth', | |
labelWater: 'Water', | |
labelAir: 'Air', | |
generateButton: 'Generate', | |
clearButton: 'Clear', | |
selectLanguage: 'Select Language:', | |
magicSquareTrue: 'The table is a magic square with a magical number of', | |
magicSquareFalse: 'The table is not a magic square with a magical number of', | |
quotientText: 'Quotient (first cell):', | |
remainingNumberText: 'Remaining number:', | |
cellIncreasedText: 'Cell increased by 1:', | |
direction: 'ltr' | |
}, | |
fa: { | |
title: 'تولید جدول وفق', | |
labelMagicalNumber: 'عدد وفق را وارد کنید:', | |
labelOrderType: 'نوع ترتیب را وارد کنید:', | |
labelFire: 'آتش', | |
labelEarth: 'خاک', | |
labelWater: 'آب', | |
labelAir: 'باد', | |
generateButton: 'تولید', | |
clearButton: 'پاک کردن', | |
selectLanguage: 'انتخاب زبان:', | |
magicSquareTrue: 'جدول وفق دارد:', | |
magicSquareFalse: 'جدول وفق ندارد:', | |
quotientText: 'خارج قسمت (اولین خانه):', | |
remainingNumberText: 'عدد باقی مانده:', | |
cellIncreasedText: 'خانه افزایش یافته به 1:', | |
direction: 'rtl' | |
} | |
}; | |
function setLanguage() { | |
const selectedLanguage = document.getElementById('languageSelect').value; | |
const translation = translations[selectedLanguage]; | |
document.getElementById('title').textContent = translation.title; | |
document.getElementById('labelMagicalNumber').textContent = translation.labelMagicalNumber; | |
document.getElementById('labelOrderType').textContent = translation.labelOrderType; | |
document.getElementById('labelFire').textContent = translation.labelFire; | |
document.getElementById('labelEarth').textContent = translation.labelEarth; | |
document.getElementById('labelWater').textContent = translation.labelWater; | |
document.getElementById('labelAir').textContent = translation.labelAir; | |
document.getElementById('generateButton').textContent = translation.generateButton; | |
document.getElementById('clearButton').textContent = translation.clearButton; | |
document.querySelector('label[for="languageSelect"]').textContent = translation.selectLanguage; | |
document.body.style.direction = translation.direction; | |
} | |
async function generateMagicSquare() { | |
const selectedLanguage = document.getElementById('languageSelect').value; | |
const translation = translations[selectedLanguage]; | |
const magicalNumber = parseInt(document.getElementById('magicalNumber').value); | |
const orderType = document.querySelector('input[name="orderType"]:checked')?.value; | |
if (!magicalNumber || !orderType) { | |
alert("Please enter a valid magical number and select order type ('fire', 'earth', 'water', or 'air')."); | |
return; | |
} | |
const { table, quotient, remainder, cellAdjusted } = createTable(magicalNumber, orderType); | |
await displayTableAnimated(table); | |
let resultText = `${translation.quotientText} ${quotient}<br>`; | |
if (remainder > 0) { | |
resultText += `${translation.remainingNumberText} ${remainder}<br>`; | |
resultText += `${translation.cellIncreasedText} ${cellAdjusted}<br>`; | |
} | |
const isMagicSquare = checkMagicSquare(table, magicalNumber); | |
resultText += isMagicSquare ? | |
`${translation.magicSquareTrue} ${magicalNumber}.` : | |
`${translation.magicSquareFalse} ${magicalNumber}.`; | |
document.getElementById('result').innerHTML += resultText; | |
} | |
function clearResults() { | |
document.getElementById('result').innerHTML = ''; | |
} | |
function createTable(magicalNumber, orderType) { | |
const quotient = Math.floor((magicalNumber - 30) / 4); | |
const remainder = (magicalNumber - 30) % 4; | |
const table = Array.from({ length: 16 }, (_, i) => quotient + i); | |
let cellAdjusted = null; | |
if (remainder === 1) { | |
for (let i = 12; i < 16; i++) table[i]++; | |
cellAdjusted = 13; | |
} else if (remainder === 2) { | |
for (let i = 8; i < 16; i++) table[i]++; | |
cellAdjusted = 9; | |
} else if (remainder === 3) { | |
for (let i = 4; i < 16; i++) table[i]++; | |
cellAdjusted = 5; | |
} | |
const fireOrder = [8, 11, 14, 1, 13, 2, 7, 12, 3, 16, 9, 6, 10, 5, 4, 15]; | |
const earthOrder = [5, 4, 15, 10, 16, 9, 6, 3, 2, 7, 12, 13, 11, 14, 1, 8]; | |
const waterOrder = [6, 9, 16, 3, 15, 4, 5, 10, 1, 14, 11, 8, 12, 7, 2, 13]; | |
const airOrder = [10, 15, 4, 5, 8, 1, 14, 11, 13, 12, 7, 2, 3, 6, 9, 16]; | |
let order; | |
switch (orderType) { | |
case 'fire': | |
order = fireOrder; | |
break; | |
case 'earth': | |
order = earthOrder; | |
break; | |
case 'water': | |
order = waterOrder; | |
break; | |
case 'air': | |
order = airOrder; | |
break; | |
} | |
const tableOrdered = Array.from({ length: 16 }, (_, i) => table[order[i] - 1]); | |
const table2d = Array.from({ length: 4 }, (_, i) => tableOrdered.slice(i * 4, i * 4 + 4)); | |
return { table: table2d, quotient, remainder, cellAdjusted }; | |
} | |
async function displayTableAnimated(table) { | |
const tableElement = document.createElement('table'); | |
tableElement.setAttribute('dir', 'ltr'); // Ensures the table is LTR | |
for (let i = 0; i < 4; i++) { | |
const tr = document.createElement('tr'); | |
for (let j = 0; j < 4; j++) { | |
const td = document.createElement('td'); | |
td.textContent = ''; | |
tr.appendChild(td); | |
} | |
tableElement.appendChild(tr); | |
} | |
document.getElementById('result').appendChild(tableElement); | |
const cellMapping = []; | |
for (let rowIndex = 0; rowIndex < 4; rowIndex++) { | |
for (let colIndex = 0; colIndex < 4; colIndex++) { | |
cellMapping.push({ value: table[rowIndex][colIndex], row: rowIndex, col: colIndex }); | |
} | |
} | |
cellMapping.sort((a, b) => a.value - b.value); | |
for (let i = 0; i < cellMapping.length; i++) { | |
const cell = cellMapping[i]; | |
const tableCell = tableElement.rows[cell.row].cells[cell.col]; | |
tableCell.classList.add('highlight'); | |
await new Promise(resolve => setTimeout(resolve, 200)); // | |
tableCell.innerHTML = `${cell.value}<sup class="index">${i + 1}</sup>`; | |
tableCell.classList.remove('highlight'); | |
} | |
} | |
function checkMagicSquare(table, magicalNumber) { | |
let allEqual = true; | |
for (let i = 0; i < 4; i++) { | |
const rowSum = table[i].reduce((acc, val) => acc + val, 0); | |
if (rowSum !== magicalNumber) { | |
allEqual = false; | |
} | |
} | |
for (let i = 0; i < 4; i++) { | |
const colSum = table.reduce((acc, row) => acc + row[i], 0); | |
if (colSum !== magicalNumber) { | |
allEqual = false; | |
} | |
} | |
const diag1Sum = table.reduce((acc, row, i) => acc + row[i], 0); | |
const diag2Sum = table.reduce((acc, row, i) => acc + row[3 - i], 0); | |
if (diag1Sum !== magicalNumber || diag2Sum !== magicalNumber) { | |
allEqual = false; | |
} | |
return allEqual; | |
} | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_table(magical_number, order_type): | |
quotient = (magical_number - 30) // 4 | |
remainder = (magical_number - 30) % 4 | |
# Create the initial table with the correct order | |
table = [quotient + i for i in range(16)] | |
# Adjust specific cells based on the remainder | |
cell_adjusted = None | |
if remainder == 1: | |
for i in range(12, 16): | |
table[i] += 1 # Increment cells starting from the 13th cell | |
cell_adjusted = 13 | |
elif remainder == 2: | |
for i in range(8, 16): | |
table[i] += 1 # Increment cells starting from the 9th cell | |
cell_adjusted = 9 | |
elif remainder == 3: | |
for i in range(4, 16): | |
table[i] += 1 # Increment cells starting from the 5th cell | |
cell_adjusted = 5 | |
# Print each cell number and value before ordering | |
for i in range(16): | |
suffix = "th" | |
if (i + 1) % 10 == 1 and (i + 1) != 11: | |
suffix = "st" | |
elif (i + 1) % 10 == 2 and (i + 1) != 12: | |
suffix = "nd" | |
elif (i + 1) % 10 == 3 and (i + 1) != 13: | |
suffix = "rd" | |
print(f"{i + 1}{suffix}: {table[i]}") | |
# Define the orders | |
fire_order = [8, 11, 14, 1, | |
13, 2, 7, 12, | |
3, 16, 9, 6, | |
10, 5, 4, 15] | |
earth_order = [5, 4, 15, 10, | |
16, 9, 6, 3, | |
2, 7, 12, 13, | |
11, 14, 1, 8] | |
# Select the appropriate order based on user input | |
if order_type.lower() == 'fire': | |
order = fire_order | |
elif order_type.lower() == 'earth': | |
order = earth_order | |
else: | |
raise ValueError("Invalid order type. Choose 'fire' or 'earth'.") | |
# Order the table according to the selected pattern | |
table_ordered = [0] * 16 | |
for i, pos in enumerate(order): | |
table_ordered[i] = table[pos - 1] | |
# Convert the ordered flat list into a 4x4 2D list | |
table_2d = [table_ordered[i:i + 4] for i in range(0, 16, 4)] | |
return table_2d, quotient, remainder, cell_adjusted | |
def print_table(table): | |
# Find the maximum length of the numbers in the table | |
max_length = max(len(str(cell)) for row in table for cell in row) | |
cell_width = max_length + 2 # Add padding for better readability | |
border = "+" + "+".join("-" * cell_width for _ in range(4)) + "+" | |
print(border) | |
for row in table: | |
print("| " + " | ".join(f"{cell:>{max_length}}" for cell in row) + " |") | |
print(border) | |
def check_magic_square(table, magical_number): | |
size = len(table) | |
all_equal = True | |
# Check rows | |
for i in range(size): | |
row_sum = sum(table[i]) | |
if row_sum != magical_number: | |
all_equal = False | |
print(f"Row {i+1} does not match: {table[i]} (sum: {row_sum})") | |
# Check columns | |
for i in range(size): | |
col_sum = sum(row[i] for row in table) | |
if col_sum != magical_number: | |
all_equal = False | |
col_values = [row[i] for row in table] | |
print(f"Column {i+1} does not match: {col_values} (sum: {col_sum})") | |
# Check diagonals | |
diag1_sum = sum(table[i][i] for i in range(size)) | |
diag2_sum = sum(table[i][size-1-i] for i in range(size)) | |
if diag1_sum != magical_number: | |
all_equal = False | |
diag1_values = [table[i][i] for i in range(size)] | |
print(f"Main diagonal does not match: {diag1_values} (sum: {diag1_sum})") | |
if diag2_sum != magical_number: | |
all_equal = False | |
diag2_values = [table[i][size-1-i] for i in range(size)] | |
print(f"Secondary diagonal does not match: {diag2_values} (sum: {diag2_sum})") | |
return all_equal | |
# Get the magical number and order type from the user | |
magical_number = int(input("Enter the magical number: ")) | |
order_type = input("Enter the order type ('fire' or 'earth'): ") | |
# Create the table | |
table, quotient, remainder, cell_adjusted = create_table(magical_number, order_type) | |
# Print the table | |
print_table(table) | |
# Print the quotient, remaining number, and the adjusted cell | |
print(f"Quotient (1st cell): {quotient}") | |
if remainder > 0: | |
print(f"Remaining number: {remainder}") | |
print(f"Cell {cell_adjusted} was incremented by +1") | |
# Check if it's a magic square and print mismatches | |
if check_magic_square(table, magical_number): | |
print(f"The table is a magic square with the magical number {magical_number}.") | |
else: | |
print(f"The table is NOT a magic square with the magical number {magical_number}.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_table(magical_number, order_type): | |
quotient = (magical_number - 30) // 4 | |
remainder = (magical_number - 30) % 4 | |
# Create the initial table with the correct order | |
table = [quotient + i for i in range(16)] | |
# Adjust specific cells based on the remainder | |
cell_adjusted = None | |
if remainder == 1: | |
for i in range(12, 16): | |
table[i] += 1 # Increment cells starting from the 13th cell | |
cell_adjusted = 13 | |
elif remainder == 2: | |
for i in range(8, 16): | |
table[i] += 1 # Increment cells starting from the 9th cell | |
cell_adjusted = 9 | |
elif remainder == 3: | |
for i in range(4, 16): | |
table[i] += 1 # Increment cells starting from the 5th cell | |
cell_adjusted = 5 | |
# Print each cell number and value before ordering | |
for i in range(16): | |
suffix = "th" | |
if (i + 1) % 10 == 1 and (i + 1) != 11: | |
suffix = "st" | |
elif (i + 1) % 10 == 2 and (i + 1) != 12: | |
suffix = "nd" | |
elif (i + 1) % 10 == 3 and (i + 1) != 13: | |
suffix = "rd" | |
print(f"{i + 1}{suffix}: {table[i]}") | |
# Define the orders | |
fire_order = [8, 11, 14, 1, | |
13, 2, 7, 12, | |
3, 16, 9, 6, | |
10, 5, 4, 15] | |
earth_order = [5, 4, 15, 10, | |
16, 9, 6, 3, | |
2, 7, 12, 13, | |
11, 14, 1, 8] | |
# Select the appropriate order based on user input | |
if order_type.lower() == 'fire': | |
order = fire_order | |
elif order_type.lower() == 'earth': | |
order = earth_order | |
else: | |
raise ValueError("نوع ترتیب نامعتبر است. 'fire' یا 'earth' را انتخاب کنید.") | |
# Order the table according to the selected pattern | |
table_ordered = [0] * 16 | |
for i, pos in enumerate(order): | |
table_ordered[i] = table[pos - 1] | |
# Convert the ordered flat list into a 4x4 2D list | |
table_2d = [table_ordered[i:i + 4] for i in range(0, 16, 4)] | |
return table_2d, quotient, remainder, cell_adjusted | |
def print_table(table): | |
# Find the maximum length of the numbers in the table | |
max_length = max(len(str(cell)) for row in table for cell in row) | |
cell_width = max_length + 2 # Add padding for better readability | |
border = "+" + "+".join("-" * cell_width for _ in range(4)) + "+" | |
print(border) | |
for row in table: | |
print("| " + " | ".join(f"{cell:>{max_length}}" for cell in row) + " |") | |
print(border) | |
def check_magic_square(table, magical_number): | |
size = len(table) | |
all_equal = True | |
# Check rows | |
for i in range(size): | |
row_sum = sum(table[i]) | |
if row_sum != magical_number: | |
all_equal = False | |
print(f"سطر {i+1} مطابقت ندارد: {table[i]} (مجموع: {row_sum})") | |
# Check columns | |
for i in range(size): | |
col_sum = sum(row[i] for row in table) | |
if col_sum != magical_number: | |
all_equal = False | |
col_values = [row[i] for row in table] | |
print(f"ستون {i+1} مطابقت ندارد: {col_values} (مجموع: {col_sum})") | |
# Check diagonals | |
diag1_sum = sum(table[i][i] for i in range(size)) | |
diag2_sum = sum(table[i][size-1-i] for i in range(size)) | |
if diag1_sum != magical_number: | |
all_equal = False | |
diag1_values = [table[i][i] for i in range(size)] | |
print(f"قطر اصلی مطابقت ندارد: {diag1_values} (مجموع: {diag1_sum})") | |
if diag2_sum != magical_number: | |
all_equal = False | |
diag2_values = [table[i][size-1-i] for i in range(size)] | |
print(f"قطر فرعی مطابقت ندارد: {diag2_values} (مجموع: {diag2_sum})") | |
return all_equal | |
# Get the magical number and order type from the user | |
magical_number = int(input("عدد وفق را وارد کنید: ")) | |
order_type = input("نوع ترتیب را وارد کنید ('fire' یا 'earth'): ") | |
# Create the table | |
table, quotient, remainder, cell_adjusted = create_table(magical_number, order_type) | |
# Print the table | |
print_table(table) | |
# Print the quotient, remaining number, and the adjusted cell | |
print(f"خارج قسمت (اولین خانه): {quotient}") | |
if remainder > 0: | |
print(f"عدد باقیمانده: {remainder}") | |
print(f"خانه {cell_adjusted} با مقدار یک واحد افزایش یافت") | |
# Check if it's a magic square and print mismatches | |
if check_magic_square(table, magical_number): | |
print(f"جدول یک مربع وفق با عدد وفق {magical_number} است.") | |
else: | |
print(f"جدول یک مربع وفق با عدد وفق {magical_number} نیست.") |
Author
mshafiee
commented
Jun 5, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment