{"id":21289134,"url":"https://github.com/mogalina/complexnumberscalculator","last_synced_at":"2025-03-15T15:44:42.422Z","repository":{"id":258650951,"uuid":"870360183","full_name":"Mogalina/ComplexNumbersCalculator","owner":"Mogalina","description":"Calculator for expressions consisting of complex numbers.","archived":false,"fork":false,"pushed_at":"2024-10-17T17:16:55.000Z","size":476,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-22T05:42:56.713Z","etag":null,"topics":["calculator","complex-numbers","design-patterns","factory-method-design-pattern","java","oop-principles","singleton-design-pattern","template-method-design-pattern"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Mogalina.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-09T22:38:32.000Z","updated_at":"2024-10-17T17:16:58.000Z","dependencies_parsed_at":"2024-10-20T01:35:05.494Z","dependency_job_id":null,"html_url":"https://github.com/Mogalina/ComplexNumbersCalculator","commit_stats":null,"previous_names":["mogalina/complexnumberscalculator"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mogalina%2FComplexNumbersCalculator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mogalina%2FComplexNumbersCalculator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mogalina%2FComplexNumbersCalculator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mogalina%2FComplexNumbersCalculator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Mogalina","download_url":"https://codeload.github.com/Mogalina/ComplexNumbersCalculator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243754008,"owners_count":20342537,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["calculator","complex-numbers","design-patterns","factory-method-design-pattern","java","oop-principles","singleton-design-pattern","template-method-design-pattern"],"created_at":"2024-11-21T12:34:38.428Z","updated_at":"2025-03-15T15:44:42.394Z","avatar_url":"https://github.com/Mogalina.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Complex Numbers Calculator\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Features](#features)\n- [Installation](#installation)\n- [Usage](#usage)\n- [Code Overview](#code-overview)\n- [Examples](#examples)\n\n## Overview\n\n### Why Java\n\nJava is a versatile, high-performance programming language widely used for developing applications ranging from mobile \napps to large-scale enterprise systems. Here's why we chose Java for this project:\n\n- **Platform Independence**\n    \n  Java's \"Write Once, Run Anywhere\" capability allows the application to run on any system with a Java Virtual Machine\n  (JVM).\n\n\n- **Strong Community \u0026 Ecosystem**\n\n  Java has a rich ecosystem of libraries and frameworks and excellent support from a large community.\n\n\n- **Object-Oriented \u0026 Scalable**\n\n  Java’s object-oriented principles ensure modular and maintainable code, while its scalability makes it suitable for \n  both small and enterprise-level applications.\n\n\n- **Performance \u0026 Security**\n\n  Modern JVMs optimize Java's performance to compete with lower-level languages, and built-in security features make \n  it a trusted choice for secure applications.\n\n\n- **Multithreading**\n\n  Java supports concurrent programming, allowing the efficient execution of multiple tasks simultaneously, making it \n  ideal for complex systems.\n\n### Project Description\n\nThe **Complex Numbers Calculator** is an object-oriented application designed to perform various arithmetic operations\n([ADDITION](#addition), [SUBSTRACTION](#substraction), [DIVISION](#division), [MULTIPLICATION](#multiplication)) \n**strictly** on complex numbers. \n\nThe code remains modular and maintainable by adhering to OOP principles such as:\n\n- **DRY (Don't Repeat Yourself)**\n- **SRP (Single Responsibility Principle)**\n\nMoreover, to enhance flexibility and scalability in the application's architecture, it utilizes **Software Design \nPatterns** such as:\n\n- [**Singleton**](https://en.wikipedia.org/wiki/Singleton_pattern)\n- [**Factory**](https://en.wikipedia.org/wiki/Factory_method_pattern)\n\nTo **find more** about the project, check the `JavaDoc` using the following command based on your operating system\n(**make sure** you are currently located in the *project directory*):\n\n- **macOS**\n\n  ```bash\n  open ./src/resources/index.html\n  ```\n\n- **Linux**\n\n  ```bash\n  xdg-open ./src/resources/index.html\n  ```\n\n- **Windows**\n\n  ```bash\n  start .\\src\\resources\\index.html\n  ```\n\n## Features\n\nThe **Complex Numbers Calculator** includes a various range of functionalities to perform arithmetic operations and\nmanipulate complex numbers efficiently.\n\n- **Arithmetic Operations**\n\n    \u003e Let's consider two complex numbers ***z_1*** and ***z_2*** such that:\n    \u003e \n    \u003e\u003e _z_1 = a_1 + b_1 * i_\n    \u003e\u003e     \n    \u003e\u003e _z_2 = a_2 + b_2 * i_\n    \u003e\u003e \n    \u003e\u003e Where { _a_1_, _b_1_, _a_2_, _b_2_ } are considered ***Real Numbers***\n    \u003e  \n    \u003e Based on their composition, we deduce the following operations. \n  - [**Addition**](#addition)\n    ```\n    z_1 + z_2 = (a_1 + a_2) + (b_1 + b_2) * i\n    ```\n  - [**Substraction**](#substraction)\n    ```\n    z_1 - z_2 = (a_1 - a_2) + (b_1 - b_2) * i\n    ```\n  - [**Division**](#division)\n    ```\n    z_1 / z_2 = [(a_1 * a_2 + b_1 * b_2) + (b_1 * a_2 - a_1 * b_2) * i] / (a_2 ^ 2 + b_2 ^ 2)\n    ```\n  - [**Multiplication**](#multiplication)\n    ```\n    z_1 * z_2 = (a_1 * a_2 - b_1 * b_2) + (a_1 * b_2 + b_1 * a_2) * i\n    ```\n    \n\n- **Conjugate Calculation**\n  \n  The conjugate of a complex number is useful in various mathematical applications.\n  \n  \u003e Let's consider one complex numbers ***z*** such that:\n  \u003e\n  \u003e\u003e _z = a + b * i_\n  \u003e\u003e\n  \u003e\u003e Where { _a_, _b_ } are considered ***Real Numbers***\n  \u003e \n  \u003e Therefore, we define the conjugate as:\n  \u003e\n  \u003e\u003e  _z = a - b * i_\n  \n\n- **Input Parsing**\n  \n  The calculator can accept ***(via Command Line Interface / CLI)*** complex numbers in standard form ***(eg. a + b * \n  i)***, allowing for intuitive user input.\n\n\n- **Error Handling**\n\n  Robust error handling for invalid inputs and operations, ensuring a smooth user experience.\n\n\n- **Extensibility**\n\n  The design supports easy addition of new features, such as advanced mathematical operations or graphical user \n  interfaces, thanks to the application of OOP principles and design patterns.\n\n## Installation\n\n### Prerequisites\n  \nBefore installing and running the application, ensure that the following prerequisites are met:\n\n#### **Java Development Kit (JDK)**\n  \nYou need **JDK 8** or higher installed on your system. To check if it is installed, run in terminal:\n  \n```bash\njava -version\n```\n  \nIf you don't have it installed, you can download the JDK from \n[Oracle's official website](https://www.oracle.com/java/technologies/downloads/?er=221886).\n\n\n### Clone the Repository\n\nTo get started, clone the repository from GitHub to your local machine. In terminal, nagivate to the directory you\nwhere you want to store the project, and run:\n  \n```bash\ngit clone https://github.com/Mogalina/ComplexNumbersCalculator.git\n```\n\n### Compile the Project Using JDK\n\nOnce you have cloned your project, navigate into the project directory:\n\n```bash\ncd ComplexNumbersCalculator\n```\n\nTo compile the Java files, use the ```javac``` command to compile all the files in the ```src``` directory:\n\n```bash\njavac -d out -sourcepath src src/**/*.java\n```\n\nThis command will do the following:\n\n- Compile all the ```.java``` files located in the specified directories.\n- Store the compiled ```.class``` files in the ```out/``` directory.\n\n### Run the Application\n\nAfter compiling, you can run the application using the ```java``` command. From your project root directory, execute the\nmain class that contains the ```main``` method:\n\n```bash\njava -cp out Main\n```\n\n## Usage\n\nAfter installing the application, follow the steps below to run and use the **Complex Numbers Calculator**.\n\n### Running the Application\n\nOnce you’ve successfully built or compiled the project, you can run the application directly from the terminal or your \nIDE.\n\n#### Running via Terminal (using JDK)\n\nIf you compiled the project using the **JDK** and the compiled files are located in the `out/` directory, you can run the application using the `java` command. Navigate to the root of your project and run:\n\n```bash\njava -cp out Main\n```\n\n#### Running via IDE\n\nIf you’re using an IDE like *IntelliJ IDEA* or *Eclipse*, follow these steps:\n\n- Open the project in your IDE.\n- Locate the class containing the ```main``` method (usually ```Main.java``` or equivalent).\n- Right-Click on the file and select ```Run```.\n- The application will start, and you’ll be able to interact with it via the IDE's terminal.\n\n### Interacting with the Calculator\n\nThe *Complex Numbers Calculator* supports a various range of arithmetic operations on complex numbers. You **must**\nrun the expression using the ```java``` command **in terminal** as follows:\n\n#### Complex Number Structure\n\nEach complex number must have the following structre **with no spaces between**: ```a+b*i```.\n\n#### Operands and Operators\n\nBetween **each** operator and operand there **must** exist **at least** one space: ```a+b*i op c+d*i```. Operators \n**must** be one of ```+ - * /```.\n\n#### Calculating the Result\n\nTo calculate the result of an arithmetic expression containing **exclusively** complex numbers, in **terminal** run the\nfollowing using ```java``` command:\n\n```bash\njava -cp out Main complex_number operator complex_number operator complex_number ...\n```\n\n## Code Overview\n\n- [**Main.java**](#main)\n- [**/resources**](#documentation)\n- [**/enums**](#enums)\n- [**/factory**](#factory)\n- [**/models**](#models)\n\n### Main.java\n\nThis `class` represents the **entry point** of the application. It initializes the program, handles user input, and\norchestrates the calculation operations.\n\n#### Methods\n\n##### `main(String[] args)`\n\n- Starts the application and manages user interactions.\n- Creates an `ExpressionParser` object to handle the parsing and evaluation of the arithmetic expression.\n\n### /resources\n\nThis folder stores information about the application and project structure, including the relationship between `classes`\n, `packages` and `modules`.\n\n#### UML.png\n\nThis `.png` file represents the \n[**UML (Unified Modeling Language)**](#https://en.wikipedia.org/wiki/Unified_Modeling_Language) diagram that stores\ninformation about the relationship between `classes`, `packages` and `modules`.\n\n### /enums\n\nThis `package` stores `enum` classes to define collections of **constants** that are grouped together under **a single\ntype**. The purpose of `enum` classes is to enhance **type safety** and make code more **readable** and \n**maintainable**.\n\n#### `Operation`\n\n```java\npublic enum Operation {\n    ADDITION,\n    SUBTRACTION,\n    MULTIPLICATION,\n    DIVISION\n}\n```\n\nDefines the **supported operations** on arithmetic expressions.\n\n### /factory\n\nThis `package` contains `classes` that follow the \n[**Factory Method Pattern**](#https://en.wikipedia.org/wiki/Factory_method_pattern#Java). The purpose of this *design\npattern* is to use *factory methods* to deal with the problem of **creating objects** without having to specify their\nexact classes.\n\n### `ExpressionFactory`\n\nThis `class` is responsible for creating expressions (`subclasses`) that belong to the same family (`class`), but with\ndifferent behaviors (**ADDITION**, **SUBSTRACTION**, **MULTIPLICATION**, **DIVISION**). It utilizes two key software \ndesign patterns: the [**Factory Pattern**](#https://en.wikipedia.org/wiki/Factory_method_pattern#Java) and the \n[**Singleton Pattern**](#https://en.wikipedia.org/wiki/Singleton_pattern).\n\n##### Why use Factory here?\n\n```java\npublic ComplexExpression createExpression(@NotNull Operation operation, ComplexNumber[] args) {\n    return switch (operation) {\n        case ADDITION -\u003e new AdditionExpression(args);\n        case SUBTRACTION -\u003e new SubtractionExpression(args);\n        case MULTIPLICATION -\u003e new MultiplicationExpression(args);\n        case DIVISION -\u003e new DivisionExpression(args);\n        default -\u003e throw new IllegalArgumentException(\"Unknown operation\");\n    };\n}\n```\n\n- **Encapsulation of Object Creation** : The client code doesn’t need to know which specific class to instantiate, it \n  just specifies the operation, and the factory handles the rest.\n\n\n- **Flexibility and Extensibility** : If more operations are added in the future, it’s easy to extend the factory to \n  create instances of the new expression types without changing the client code.\n\n\n- **Centralized Creation Logic** : All logic for creating complex expression objects is centralized within the factory, \n  promoting consistency and reducing code duplication across the application.\n\n##### Why use Singleton here?\n\n```java\nprivate ExpressionFactory() {}\n```\n\nThe `constructor` is private, preventing external `classes` from instantiating it dirrectly.\n\n```java\nprivate static ExpressionFactory instance = null;\n```\n\nThe `class` has a static variable `instance` that holds the single instance of `ExpressionFactory`.\n\n```java\npublic static ExpressionFactory getInstance() {\n    if (instance == null) {\n        instance = new ExpressionFactory();\n    }\n    return instance;\n}\n```\n\nChecks if the `instance` exists. If so, it initializes the `instance` and returns it, otherwise it returns the already\ncreated `instance`. This ensures that the factory is only created when **needed** (***Lazy Initialization***).\n\nTherefore, the benefits of using **Singleton Method** here are the following:\n\n- **Resource Efficiency** : Since this `class` is responsible for creating `ComplexExpression` `objects`, ensuring that \n  **only one** `ExpressionFactory` instance exists means **fewer resources** are used and the application avoids \n  unnecessary object creation.\n\n\n- **Centralized Control** : Having a **single** `instance` of the factory centralizes the creation logic for \n  `ComplexExpression` `objects`, allowing **better control** over how these objects are instantiated and ensures \n  **consistency**.\n\n\n- **Global Access** : Since the factory provides complex expressions for different parts of the application, the \n  **Singleton** pattern ensures global access to the factory from **anywhere** in the codebase.\n\n##### Benefits of using both together?\n\n- **Separation of Concerns (SoC)** : The `ExpressionFactory` isolates the creation of `ComplexExpression` `objects` from \n  the client code, meaning the client only cares about using the created object, **not how it’s created**.\n\n\n- **Scalability** : Adding **new types** of `ComplexExpression` `objects` is easy. You only need to modify the factory \n  method to handle new types of expressions, without needing to change the code that uses the factory.\n\n\n- **Controlled Instantiation** : The **Singleton Pattern** ensures that **only one** `instance` of the factory exists, \n  preventing multiple factories from being created **unnecessarily** and conserving *memory resources*.\n\n### /models\n\nThis `package` contains `classes` that are the **core domain objects** of the application. These `classes` represent\nabstract concepts specific to the application.\n\n### `ComplexNumber`\n\nThis `class` defines a *complex number* with *real* and *imaginary* parts.\n\n#### Fields\n\n| Access    | Type        | Name | Description                           |\n|-----------|-------------|------|---------------------------------------|\n| `private` | `final int` | `re` | Real part of the complex number.      |\n| `private` | `final int` | `im` | Imaginary part of the complex number. |\n\n#### Methods\n\n- `public ComplexNumber(int re, int im)`\n\n  Constructs a new `ComplexNumber` with the specified *real* and *imaginary* parts.\n\n\n- `public ComplexNumber add(@NotNull ComplexNumber other)`\n\n  Adds this *complex number* to another *complex number*.\n\n\n- `public ComplexNumber subtract(@NotNull ComplexNumber other)`\n\n  Subtracts another *complex number* from this *complex number*.\n\n\n- `public ComplexNumber multiply(@NotNull ComplexNumber other)`\n\n  Multiplies this *complex number* by another *complex number*.\n\n\n- `public ComplexNumber divide(@NotNull ComplexNumber other)`\n\n  Divides this *complex number* by another *complex number*.\n\n\n- `public ComplexNumber conjugate()`\n\n  Returns the **conjugate** of this *complex number*.\n\n\n- `@Override public String toString()`\n\n  Returns a **string representation** of the *complex number*.\n\n### `ComplexExpression`\n\n**Abstract** `class` representing an *arithmetic expression* involving *complex numbers*.\n\n#### Fields\n\n| Access      | Type              | Name        | Description                                           |\n|-------------|-------------------|-------------|-------------------------------------------------------|\n| `protected` | `Operation`       | `operation` | The operation to be performed on the complex numbers. |\n| `protected` | `ComplexNumber[]` | `args`      | Array of complex numbers involved in the expression.  |\n\n#### Methods\n\n- `public ComplexExpression(Operation operation, ComplexNumber[] args)`\n  \n  **Constructor** to initialize the *complex expression* with a specific *operation* and a list of *complex numbers* \n  as arguments.\n\n\n- `public ComplexNumber execute()`\n\n  Executes the *complex expression* by sequentially applying the specified *operation* on **all** *complex numbers*\n  provided as arguments.\n\n\n- `protected abstract ComplexNumber executeOneOperation(ComplexNumber c1, ComplexNumber c2);`\n\n  **Abstract method** to perform a **single** *operation* between two *complex numbers*.\n\n### `AdditionExpression`\n\nClass representing a complex **addition** expression. This `class` **extends** the `ComplexExpression` `class`.\n\n#### Methods\n\n- `public AdditionExpression(ComplexNumber[] args)`\n\n  **Constructor** that initializes an **addition** expression with the given *complex numbers*.\n\n\n- `@Override protected ComplexNumber executeOneOperation(@NotNull ComplexNumber c1, ComplexNumber c2)`\n\n  Performs the **addition** of two *complex numbers*.\n\n### `SubtractionExpression`\n\nClass representing a complex **substraction** expression. This `class` **extends** the `ComplexExpression` `class`.\n\n#### Methods\n\n- `public SubtractionExpression(ComplexNumber[] args)`\n\n  **Constructor** that initializes a **substraction** expression with the given *complex numbers*.\n\n\n- `@Override protected ComplexNumber executeOneOperation(@NotNull ComplexNumber c1, ComplexNumber c2)`\n\n  Performs the **substraction** of two *complex numbers*.\n\n### `MultiplicationExpression`\n\nClass representing a complex **multiplication** expression. This `class` **extends** the `ComplexExpression` `class`.\n\n#### Methods\n\n- `public MultiplicationExpression(ComplexNumber[] args)`\n\n  **Constructor** that initializes a **multiplication** expression with the given *complex numbers*.\n\n\n- `@Override protected ComplexNumber executeOneOperation(@NotNull ComplexNumber c1, ComplexNumber c2)`\n\n  Performs the **multiplication** of two *complex numbers*.\n\n### `DivisionExpression`\n\nClass representing a complex **division** expression. This `class` **extends** the `ComplexExpression` `class`.\n\n#### Methods\n\n- `public DivisionExpression(ComplexNumber[] args)`\n\n  **Constructor** that initializes a **multiplication** expression with the given *complex numbers*.\n\n\n- `@Override protected ComplexNumber executeOneOperation(@NotNull ComplexNumber c1, ComplexNumber c2)`\n\n  Performs the **division** of two *complex numbers*.\n\n### `ExpressionParser`\n\nClass responsible for **parsing** complex number expressions from `CLI`.\n\n#### Fields\n\n| Access      | Type                   | Name                     | Description                              |\n|-------------|------------------------|--------------------------|------------------------------------------|\n| `private`   | `static final Pattern` | `COMPLEX_NUMBER_PATTERN` | Regex to validate complex number format. |\n\n#### Methods\n\n- `public ComplexNumber parse(String @NotNull [] args)`\n\n  **Parses** the command line arguments representing a complex number expression.\n\n\n- `private boolean isComplexNumber(String str)`\n\n  Checks if the given `string` is a **valid** *complex number*.\n\n\n- `private ComplexNumber parseComplexNumber(String str)`\n\n  Parses a *complex number* from a `string` and returns a `ComplexNumber` `object`.\n\n\n- `private boolean isOperator(@NotNull String str)`\n\n  Checks if the given `string` is a **valid** *operator*.\n\n\n- `private ComplexExpression createExpression(ComplexNumber @NotNull [] numbers, String @NotNull [] operators)`\n\n  Creates an `instance` of `ComplexExpression` based on the parsed *complex numbers* and *operators*.\n\n## Examples\n\nBased on the application [Usage](#usage), you can run the following arithmetic expressions:\n\n### Addition\n\nRun the arithmetic expression:\n\n```bash\njava -cp out Main 2+3*i + 5-6*i + -2+1*i\n```\n\nThe returned result will be:\n\n```bash\nExpression result = 5-2*i\n```\n\n### Substraction\n\nRun the arithmetic expression:\n\n```bash\njava -cp out Main 5-6*i - 2+3*i\n```\n\nThe returned result will be:\n\n```bash\nExpression result = 3-9*i\n```\n\n### Division\n\nRun the arithmetic expression:\n\n```bash\njava -cp out Main 17-6*i / 2+3*i\n```\n\nThe returned result will be:\n\n```bash\nExpression result = 1-4*i\n```\n\n### Multiplication\n\nRun the arithmetic expression:\n\n```bash\njava -cp out Main 5-6*i * 2+3*i\n```\n\nThe returned result will be:\n\n```bash\nExpression result = 28+3*i\n```\n\n### Summary of Supported Operations\n\n| Operation       | Description                                         | Example Input            | Example Output |\n|-----------------|-----------------------------------------------------|--------------------------|----------------|\n| Addition        | Adds two complex numbers.                           | `2+3*i + 5-6*i + -2+1*i` | `5-2*i`        |\n| Subtraction     | Subtracts the second complex number from the first. | `5-6*i - 2+3*i`          | `3-9*i`        |\n| Multiplication  | Multiplies two complex numbers.                     | `5-6*i * 2+3*i`          | `28+3*i`       |\n| Division        | Divides the first complex number by the second.     | `17-6*i / 2+3*i`         | `1-4*i`        |","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmogalina%2Fcomplexnumberscalculator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmogalina%2Fcomplexnumberscalculator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmogalina%2Fcomplexnumberscalculator/lists"}