Queen Attack in Cobol: Complete Solution & Deep Dive Guide
Queen Attack in Cobol: The Complete Guide to Chess Logic Programming
The Queen Attack problem is a classic programming puzzle that challenges you to determine if two queens on a chessboard can attack each other. Solving this requires checking for shared rows, columns, or diagonals. This guide provides a complete, step-by-step solution using Cobol, demonstrating core logical and arithmetic operations in this powerful, structured language.
Have you ever looked at a chessboard and seen not just a game, but a grid of pure logic? Each piece moves with a set of unbreakable rules, creating a perfect environment for a programming challenge. The queen, with her ability to dominate rows, columns, and diagonals, presents a particularly interesting problem. Now, imagine translating that logic into one of the most structured and enduring programming languages ever created: Cobol.
Many developers might feel a bit intimidated when faced with Cobol's verbose syntax and rigid structure, especially for a geometric problem like this. You might be wondering, "How do I handle coordinates? How do I calculate diagonal attacks without complex graphics libraries?" This guide is here to demystify the process. We will walk you through building a robust Cobol program from scratch that solves the Queen Attack puzzle, proving that classic logic problems are a fantastic way to master even the most venerable programming languages.
What Exactly is the Queen Attack Problem?
The Queen Attack problem is a computational challenge derived from the game of chess. The goal is simple: given the coordinates of two queens on a standard 8x8 chessboard, you must write a program to determine if they can attack each other in a single move.
In chess, a queen is the most powerful piece. It can move any number of squares horizontally, vertically, or diagonally. Therefore, two queens can attack each other if they meet any of the following conditions:
- They are on the same row.
- They are on the same column.
- They are on the same diagonal.
The challenge for a programmer is to translate these spatial rules into mathematical and logical conditions that a computer can evaluate. We represent the board as a coordinate system, typically with rows and columns indexed from 0 to 7.
Why Solve This Classic Puzzle in Cobol?
You might ask, "Why use Cobol, a language known for business and finance, for a chess puzzle?" The answer lies in the fundamental programming principles it reinforces. Cobol's strict structure and explicit data definitions force a developer to be incredibly deliberate and clear about their logic.
Solving the Queen Attack problem in Cobol provides several key benefits:
- Mastering Data Structures: Cobol's
DATA DIVISIONrequires you to meticulously define every piece of data your program will use, from coordinates to flags. This reinforces a strong understanding of data types and memory management. - Procedural Logic: The problem is solved through a clear, step-by-step procedure. This maps perfectly to Cobol's procedural nature, where you build logic through paragraphs (
PERFORM) and sequential statements. - Mathematical Functions: It provides a practical application for using built-in functions like
FUNCTION ABSfor calculating absolute differences, a cornerstone of the diagonal attack check. - Bridging Old and New: It demonstrates that the foundational logic of computer science is language-agnostic. The same core principles apply whether you're using Python, Java, or Cobol, which is vital for developers working with or migrating legacy systems.
This exercise from the exclusive kodikra.com learning path is designed to sharpen your logical thinking and problem-solving skills within the robust framework of Cobol.
How to Implement the Queen Attack Solution in Cobol
The core of the solution involves three logical checks. We must first receive the positions of the white and black queens, validate them, and then apply our attack logic. Let's break down the implementation strategy step-by-step.
Understanding the Coordinate System and Logic
An 8x8 chessboard can be represented by a grid where rows and columns are numbered 0 through 7. A position like "c5" in chess notation needs to be translated into numerical coordinates. If 'a' is column 0, 'b' is 1, etc., and rows are 0-indexed from the bottom, then "c5" would be column 2, row 4.
However, for simplicity in our Cobol program, we will assume the input is already given as zero-indexed integer coordinates (e.g., row 3, column 2).
The attack logic translates to these mathematical conditions:
- Same Row Attack:
WhiteQueenRow = BlackQueenRow - Same Column Attack:
WhiteQueenCol = BlackQueenCol - Same Diagonal Attack: The absolute difference between their row numbers is equal to the absolute difference between their column numbers.
ABS(WhiteQueenRow - BlackQueenRow) = ABS(WhiteQueenCol - BlackQueenCol).
If any of these conditions are true, the queens can attack.
ASCII Art Diagram: Logic Flow
This diagram illustrates the decision-making process within our Cobol program after receiving the queen coordinates.
● Start Logic
│
▼
┌───────────────────────┐
│ Read Queen Positions │
│ (WhiteRow, WhiteCol) │
│ (BlackRow, BlackCol) │
└──────────┬────────────┘
│
▼
◆ Are positions valid?
╱ (0-7 range) ╲
Yes No
│ │
▼ ▼
┌───────────────────┐ ┌───────────────┐
│ Proceed to Check │ │ Display Error │
└──────────┬────────┘ │ & Stop Run │
│ └───────────────┘
▼
◆ Same Row?
╱ ╲
Yes No
│ │
▼ ▼
[Set Attack] ◆ Same Column?
╱ ╲
Yes No
│ │
▼ ▼
[Set Attack] ◆ Same Diagonal?
╱ ╲
Yes No
│ │
▼ ▼
[Set Attack] [No Attack]
│ │
└──────┬───────┘
│
▼
┌─────────────┐
│ Display Result │
└─────────────┘
│
▼
● End
The Complete Cobol Code
Here is the full source code for solving the Queen Attack problem. This program is written using GnuCOBOL (formerly OpenCOBOL), a widely available open-source compiler.
******************************************************************
* Program: Queen Attack Solver
* Author: kodikra.com
* Purpose: Determines if two queens on a chessboard can attack.
* This program is part of the exclusive kodikra.com curriculum.
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. QUEEN-ATTACK.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W-QUEEN-POSITIONS.
05 W-WHITE-QUEEN-ROW PIC 9(1) VALUE 0.
05 W-WHITE-QUEEN-COL PIC 9(1) VALUE 0.
05 W-BLACK-QUEEN-ROW PIC 9(1) VALUE 0.
05 W-BLACK-QUEEN-COL PIC 9(1) VALUE 0.
01 W-CALCULATIONS.
05 W-ROW-DIFF PIC S9(1) VALUE 0.
05 W-COL-DIFF PIC S9(1) VALUE 0.
01 W-FLAGS.
05 W-CAN-ATTACK-FLAG PIC X(1) VALUE 'N'.
88 CAN-ATTACK VALUE 'Y'.
88 CANNOT-ATTACK VALUE 'N'.
05 W-INVALID-INPUT-FLAG PIC X(1) VALUE 'N'.
88 IS-INVALID VALUE 'Y'.
PROCEDURE DIVISION.
000-MAIN-LOGIC.
* This is the main entry point of the program.
* It accepts coordinates and calls other paragraphs.
* For this example, we hardcode values. In a real app,
* you would use ACCEPT statements.
MOVE 2 TO W-WHITE-QUEEN-ROW. *> Example: White Queen at (2, 4)
MOVE 4 TO W-WHITE-QUEEN-COL.
MOVE 5 TO W-BLACK-QUEEN-ROW. *> Example: Black Queen at (5, 7)
MOVE 7 TO W-BLACK-QUEEN-COL.
PERFORM 100-VALIDATE-POSITIONS
IF IS-INVALID
DISPLAY "Error: Invalid queen position."
DISPLAY "Rows and columns must be between 0 and 7."
ELSE
PERFORM 200-CHECK-ATTACK
PERFORM 300-DISPLAY-RESULT
END-IF.
STOP RUN.
100-VALIDATE-POSITIONS.
* Checks if all coordinates are within the 0-7 board range.
IF W-WHITE-QUEEN-ROW > 7 OR W-WHITE-QUEEN-COL > 7 OR
W-BLACK-QUEEN-ROW > 7 OR W-BLACK-QUEEN-COL > 7
SET IS-INVALID TO TRUE
END-IF.
IF W-WHITE-QUEEN-ROW < 0 OR W-WHITE-QUEEN-COL < 0 OR
W-BLACK-QUEEN-ROW < 0 OR W-BLACK-QUEEN-COL < 0
SET IS-INVALID TO TRUE
END-IF.
* Also check if queens are on the same square
IF W-WHITE-QUEEN-ROW = W-BLACK-QUEEN-ROW AND
W-WHITE-QUEEN-COL = W-BLACK-QUEEN-COL
SET IS-INVALID TO TRUE
END-IF.
200-CHECK-ATTACK.
* This paragraph contains the core logic for checking attacks.
SET CANNOT-ATTACK TO TRUE. *> Reset flag before check
* Check 1: Same Row
IF W-WHITE-QUEEN-ROW = W-BLACK-QUEEN-ROW
SET CAN-ATTACK TO TRUE
END-IF.
* Check 2: Same Column
IF W-WHITE-QUEEN-COL = W-BLACK-QUEEN-COL
SET CAN-ATTACK TO TRUE
END-IF.
* Check 3: Same Diagonal
COMPUTE W-ROW-DIFF = W-WHITE-QUEEN-ROW - W-BLACK-QUEEN-ROW.
COMPUTE W-COL-DIFF = W-WHITE-QUEEN-COL - W-BLACK-QUEEN-COL.
IF FUNCTION ABS(W-ROW-DIFF) = FUNCTION ABS(W-COL-DIFF)
SET CAN-ATTACK TO TRUE
END-IF.
300-DISPLAY-RESULT.
* Displays the final result to the user.
DISPLAY "White Queen: (" W-WHITE-QUEEN-ROW ", "
W-WHITE-QUEEN-COL ")".
DISPLAY "Black Queen: (" W-BLACK-QUEEN-ROW ", "
W-BLACK-QUEEN-COL ")".
IF CAN-ATTACK
DISPLAY "Result: Queens can attack each other."
ELSE
DISPLAY "Result: Queens cannot attack each other."
END-IF.
Detailed Code Walkthrough
Let's dissect the Cobol program to understand how each part contributes to the solution.
IDENTIFICATION DIVISION
This is the simplest division. The PROGRAM-ID gives our program a name, QUEEN-ATTACK. It's standard boilerplate for any Cobol program.
DATA DIVISION
Here we define all our variables in the WORKING-STORAGE SECTION.
W-QUEEN-POSITIONS: A group item to hold the coordinates. Each coordinate (e.g.,W-WHITE-QUEEN-ROW) is defined asPIC 9(1), which means it's a single-digit numeric field.W-CALCULATIONS: This group holds variables for intermediate calculations.W-ROW-DIFFandW-COL-DIFFare defined asPIC S9(1). TheSis crucial; it allows the variable to hold a sign (positive or negative), which is necessary when subtracting coordinates.W-FLAGS: We use flags to manage the program's state.W-CAN-ATTACK-FLAGis a single character (PIC X(1)) that will be 'Y' or 'N'. We use level 88 condition names (CAN-ATTACK,CANNOT-ATTACK) to make our code more readable in thePROCEDURE DIVISION. Similarly,W-INVALID-INPUT-FLAGhandles input validation.
PROCEDURE DIVISION
This is where the program's logic resides, organized into paragraphs.
000-MAIN-LOGIC: This is the main driver. It first sets some hardcoded values for the queen positions (in a real-world scenario, you would useACCEPTto get user input). It then calls the validation paragraph. If the input is valid, it proceeds to check for an attack and display the result.100-VALIDATE-POSITIONS: A crucial step for robust programming. This paragraph checks if the coordinates are within the valid range of 0-7. It also checks if the queens are placed on the exact same square, which is an invalid state. If any check fails, it sets theIS-INVALIDflag to true.200-CHECK-ATTACK: The heart of the program. It first resets the attack flag to 'N'. Then, it performs the three key checks sequentially. Notice that we don't useELSE IF. This is intentional; it allows us to check all conditions, although a single match is enough to set the flag to 'Y'. The diagonal check uses theCOMPUTEverb to calculate the differences and the intrinsicFUNCTION ABSto find the absolute values for comparison.300-DISPLAY-RESULT: This final paragraph formats and prints the output, clearly stating the queens' positions and whether they can attack, based on the final state of theW-CAN-ATTACK-FLAG.
Compiling and Running the Program
To run this Cobol code, you need a Cobol compiler. GnuCOBOL is an excellent, free option. Once installed, you can compile and run the program from your terminal.
1. Save the code above into a file named queen-attack.cob.
2. Open your terminal or command prompt and navigate to the directory where you saved the file.
3. Compile the code using the following command:
cobc -x -free queen-attack.cob
-xtells the compiler to create an executable file.-freespecifies that the source code uses a free-format layout, which is more modern and easier to read than the old fixed-format.
4. If the compilation is successful, an executable file (queen-attack on Linux/macOS or queen-attack.exe on Windows) will be created.
5. Run the program:
./queen-attack
The program will execute and display the result based on the hardcoded coordinates in the source file.
ASCII Art Diagram: Compilation & Execution Flow
This diagram shows the journey from source code to program output.
● Start
│
▼
┌───────────────────────┐
│ Write Cobol Source │
│ (queen-attack.cob) │
└──────────┬────────────┘
│
▼
┌───────────────────────┐
│ Open Terminal / CMD │
└──────────┬────────────┘
│
▼
┌───────────────────────┐
│ Run Compiler Command │
│ `cobc -x -free ...` │
└──────────┬────────────┘
│
▼
◆ Compilation OK?
╱ ╲
Yes No
│ │
▼ ▼
┌──────────────────┐ ┌─────────────────┐
│ Executable Created │ │ Review Compiler │
│ (`queen-attack`) │ │ Errors │
└─────────┬────────┘ └─────────┬───────┘
│ │
▼ ▼
┌──────────────────┐ ● End
│ Run the Program │
│ `./queen-attack` │
└─────────┬────────┘
│
▼
┌──────────────────┐
│ View Output in │
│ Terminal │
└─────────┬────────┘
│
▼
● End
Alternative Approaches and Considerations
While the direct coordinate math approach is the most efficient for this problem, it's worth considering other methods to broaden your understanding.
Using a 2D Array (Table)
One could represent the chessboard with a 2D array or table in Cobol, like 01 CHESS-BOARD OCCURS 8 TIMES INDEXED BY I, J.. You could place markers for the queens in the array and then write procedures to iterate through rows, columns, and diagonals from each queen's position to see if the other queen is encountered.
Pros & Cons of the Coordinate Math Approach
| Pros | Cons |
|---|---|
| Highly Efficient: Requires only a few simple arithmetic operations and comparisons, making it extremely fast. | Abstract: The logic is purely mathematical and doesn't visually represent the board, which can be less intuitive for beginners. |
| Low Memory Usage: Only needs a few variables to store coordinates. No need to allocate memory for an entire 8x8 board. | Less Scalable for Board-State Problems: This approach is perfect for the two-queen problem but doesn't scale well to problems requiring knowledge of the entire board state (e.g., checking for obstructions). |
| Language-Agnostic Logic: The mathematical principles are universal and can be easily translated to any other programming language. | Prone to Off-by-One Errors: Developers must be careful with zero-indexed vs. one-indexed coordinate systems during implementation. |
For the specific problem defined in this kodikra module, the coordinate math solution is superior due to its simplicity and performance.
Frequently Asked Questions (FAQ)
- 1. Why is the `S` in `PIC S9(1)` important for the difference variables?
- The `S` specifies that the numeric field is signed, meaning it can hold a negative value. When you calculate `W-WHITE-QUEEN-ROW - W-BLACK-QUEEN-ROW`, the result could be negative (e.g., 2 - 5 = -3). Without the `S`, Cobol would store the absolute value (3), which would break the logic of the diagonal check.
- 2. What is `FUNCTION ABS`?
FUNCTION ABSis an intrinsic function in modern Cobol that returns the absolute (non-negative) value of a number. It's essential for the diagonal check because we only care about the *distance* between the queens on each axis, not the direction. The condition `ABS(row1 - row2) = ABS(col1 - col2)` holds true for both types of diagonals.- 3. Can this logic be adapted for a different-sized board?
- Absolutely. The core logic (same row, same column, same diagonal difference) is independent of board size. The only part of the code you would need to change is the `100-VALIDATE-POSITIONS` paragraph to check against the new board boundaries (e.g., 0-15 for a 16x16 board).
- 4. Why use `PERFORM` to structure the code into paragraphs?
- Using `PERFORM` to call paragraphs is a cornerstone of structured programming in Cobol. It breaks down a complex problem into smaller, manageable, and reusable pieces of logic. This makes the code easier to read, debug, and maintain, much like calling functions or methods in other languages.
- 5. What are Level 88 Condition Names?
- Level 88 items, like `88 CAN-ATTACK VALUE 'Y'`, are a powerful feature in Cobol for creating readable boolean-like conditions. Instead of writing `IF W-CAN-ATTACK-FLAG = 'Y'`, you can write the much more self-documenting `IF CAN-ATTACK`. It significantly improves code clarity.
- 6. How would I get user input instead of hardcoding values?
- You would use the `ACCEPT` verb. For example, to get the white queen's row, you could write:
DISPLAY "Enter White Queen Row (0-7): ". ACCEPT W-WHITE-QUEEN-ROW.You would do this for all four coordinate values at the beginning of the `000-MAIN-LOGIC` paragraph. - 7. Is Cobol still relevant for learning these kinds of logic puzzles?
- Yes, very much so. It forces you to think algorithmically without the high-level abstractions of modern languages. Mastering logic in a low-level, structured environment like Cobol builds a strong foundation that makes you a better programmer in any language. For more on Cobol's capabilities, explore our complete Cobol learning guide.
Conclusion: Logic, Structure, and Mastery
We've successfully navigated the Queen Attack problem, translating the elegant rules of chess into the structured, precise syntax of Cobol. By breaking the problem down into three simple checks—same row, same column, and same diagonal—we developed an efficient and readable solution. This exercise highlights how Cobol's deliberate data definitions and procedural flow are perfectly suited for implementing clear, step-by-step algorithms.
The key takeaway is that the principles of logical problem-solving are universal. Whether you're working on a mainframe system or a modern web application, the ability to dissect a problem and build a robust algorithm is the most critical skill a developer can possess. This challenge is a fantastic stepping stone in your journey to mastering computational thinking.
Ready for your next challenge? Continue your progress through the Cobol 4 learning roadmap on kodikra.com to tackle more complex problems and solidify your skills.
Technology Disclaimer: The code and commands in this article have been verified using GnuCOBOL 3.1.2. While the core Cobol logic is highly portable, syntax for specific features or compiler flags may vary slightly between different Cobol compilers (e.g., IBM Enterprise COBOL, Micro Focus Visual COBOL).
Published by Kodikra — Your trusted Cobol learning resource.
Post a Comment