From cfaa94f08e9fbb0ec08c6394da6de89a22f583f4 Mon Sep 17 00:00:00 2001 From: david-swift Date: Mon, 1 Jan 2024 11:53:04 +0100 Subject: [PATCH] Initial commit --- .github/ISSUE_TEMPLATE/bug_report.yml | 40 +++++ .github/ISSUE_TEMPLATE/feature_request.yml | 36 ++++ .github/PULL_REQUEST_TEMPLATE.md | 14 ++ .github/workflows/swiftlint.yml | 30 ++++ .gitignore | 13 ++ .swiftlint.yml | 162 ++++++++++++++++++ CONTRIBUTING.md | 35 ++++ Contributors.md | 3 + Documentation/Reference/README.md | 18 ++ .../Reference/enums/EditOperation.md | 23 +++ .../enums/LevenshteinTransformations.md | 32 ++++ .../Reference/enums/Transformation.md | 46 +++++ Documentation/Reference/extensions/Array.md | 42 +++++ Documentation/Reference/extensions/String.md | 23 +++ Documentation/Reference/structs/Functions.md | 27 +++ LICENSE.md | 21 +++ Makefile | 5 + Package.swift | 30 ++++ README.md | 96 +++++++++++ .../EditOperation.swift | 21 +++ .../Extensions/Array.swift | 68 ++++++++ .../Extensions/String.swift | 37 ++++ .../Functions.swift | 33 ++++ .../LevenshteinTransformations.swift | 138 +++++++++++++++ .../Transformation.swift | 106 ++++++++++++ Tests/LevenshteinTransformationsTests.swift | 96 +++++++++++ data/Icon.svg | 27 +++ 27 files changed, 1222 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/swiftlint.yml create mode 100644 .gitignore create mode 100644 .swiftlint.yml create mode 100644 CONTRIBUTING.md create mode 100644 Contributors.md create mode 100644 Documentation/Reference/README.md create mode 100644 Documentation/Reference/enums/EditOperation.md create mode 100644 Documentation/Reference/enums/LevenshteinTransformations.md create mode 100644 Documentation/Reference/enums/Transformation.md create mode 100644 Documentation/Reference/extensions/Array.md create mode 100644 Documentation/Reference/extensions/String.md create mode 100644 Documentation/Reference/structs/Functions.md create mode 100644 LICENSE.md create mode 100644 Makefile create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/LevenshteinTransformations/EditOperation.swift create mode 100644 Sources/LevenshteinTransformations/Extensions/Array.swift create mode 100644 Sources/LevenshteinTransformations/Extensions/String.swift create mode 100644 Sources/LevenshteinTransformations/Functions.swift create mode 100644 Sources/LevenshteinTransformations/LevenshteinTransformations.swift create mode 100644 Sources/LevenshteinTransformations/Transformation.swift create mode 100644 Tests/LevenshteinTransformationsTests.swift create mode 100644 data/Icon.svg diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..ee1a591 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,40 @@ +name: Bug report +description: Something is not working as expected. +title: Description of the bug +labels: bug + +body: + - type: textarea + attributes: + label: Describe the bug + description: >- + A clear and concise description of what the bug is. + validations: + required: true + + - type: textarea + attributes: + label: To Reproduce + description: >- + Steps to reproduce the behavior. + placeholder: | + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + + - type: textarea + attributes: + label: Expected behavior + description: >- + A clear and concise description of what you expected to happen. + validations: + required: true + + - type: textarea + attributes: + label: Additional context + description: >- + Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..c244dbb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,36 @@ +name: Feature request +description: Suggest an idea for this project +title: Description of the feature request +labels: enhancement + +body: + - type: input + attributes: + label: Is your feature request related to a problem? Please describe. + placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: false + + - type: textarea + attributes: + label: Describe the solution you'd like + placeholder: >- + A clear and concise description of what you want to happen. + validations: + required: true + + - type: textarea + attributes: + label: Describe alternatives you've considered + placeholder: >- + A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true + + - type: textarea + attributes: + label: Additional context + placeholder: >- + Add any other context or screenshots about the feature request here. + validations: + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..f0ed3f3 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +## Steps +- [ ] Add your name or username and a link to your GitHub profile into the [Contributors.md][1] file. +- [ ] Build the project on your machine. If it does not compile, fix the errors. +- [ ] Describe the purpose and approach of your pull request below. +- [ ] Submit the pull request. Thank you very much for your contribution! + +## Purpose +_Describe the problem or feature._ +_If there is a related issue, add the link._ + +## Approach +_Describe how this pull request solves the problem or adds the feature._ + +[1]: /Contributors.md diff --git a/.github/workflows/swiftlint.yml b/.github/workflows/swiftlint.yml new file mode 100644 index 0000000..5348bdb --- /dev/null +++ b/.github/workflows/swiftlint.yml @@ -0,0 +1,30 @@ +name: SwiftLint + +on: + push: + paths: + - '.github/workflows/swiftlint.yml' + - '.swiftlint.yml' + - '**/*.swift' + pull_request: + paths: + - '.github/workflows/swiftlint.yml' + - '.swiftlint.yml' + - '**/*.swift' + workflow_dispatch: + paths: + - '.github/workflows/swiftlint.yml' + - '.swiftlint.yml' + - '**/*.swift' + +jobs: + SwiftLint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: SwiftLint + uses: norio-nomura/action-swiftlint@3.2.1 + with: + args: --strict + env: + WORKING_DIRECTORY: Source diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d941c7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.DS_Store +/.build +/.flatpak-builder +/build-dir +/run +/Packages +/*.xcodeproj +/Package.resolved +xcuserdata/ +DerivedData/ +.swiftpm/config/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..441da6e --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,162 @@ +# Opt-In Rules +opt_in_rules: + - anonymous_argument_in_multiline_closure + - array_init + - attributes + - closure_body_length + - closure_end_indentation + - closure_spacing + - collection_alignment + - comma_inheritance + - conditional_returns_on_newline + - contains_over_filter_count + - contains_over_filter_is_empty + - contains_over_first_not_nil + - contains_over_range_nil_comparison + - convenience_type + - discouraged_none_name + - discouraged_object_literal + - discouraged_optional_boolean + - discouraged_optional_collection + - empty_collection_literal + - empty_count + - empty_string + - enum_case_associated_values_count + - explicit_init + - fallthrough + - file_header + - file_name + - file_name_no_space + - first_where + - flatmap_over_map_reduce + - force_unwrapping + - function_default_parameter_at_end + - identical_operands + - implicit_return + - implicitly_unwrapped_optional + - joined_default_parameter + - last_where + - legacy_multiple + - let_var_whitespace + - literal_expression_end_indentation + - local_doc_comment + - lower_acl_than_parent + - missing_docs + - modifier_order + - multiline_arguments + - multiline_arguments_brackets + - multiline_function_chains + - multiline_literal_brackets + - multiline_parameters + - multiline_parameters_brackets + - no_extension_access_modifier + - no_grouping_extension + - no_magic_numbers + - number_separator + - operator_usage_whitespace + - optional_enum_case_matching + - prefer_self_in_static_references + - prefer_self_type_over_type_of_self + - prefer_zero_over_explicit_init + - prohibited_interface_builder + - redundant_nil_coalescing + - redundant_type_annotation + - return_value_from_void_function + - shorthand_optional_binding + - sorted_first_last + - sorted_imports + - static_operator + - strict_fileprivate + - switch_case_on_newline + - toggle_bool + - trailing_closure + - type_contents_order + - unneeded_parentheses_in_closure_argument + - yoda_condition + +# Disabled Rules +disabled_rules: + - block_based_kvo + - class_delegate_protocol + - dynamic_inline + - is_disjoint + - no_fallthrough_only + - notification_center_detachment + - ns_number_init_as_function_reference + - nsobject_prefer_isequal + - private_over_fileprivate + - redundant_objc_attribute + - self_in_property_initialization + - todo + - unavailable_condition + - valid_ibinspectable + - xctfail_message + +# Custom Rules +custom_rules: + github_issue: + name: 'GitHub Issue' + regex: '//.(TODO|FIXME):.(?!.*(https://github\.com/david-swift/LevenshteinTransformations/issues/\d))' + message: 'The related GitHub issue must be included in a TODO or FIXME.' + severity: warning + + fatal_error: + name: 'Fatal Error' + regex: 'fatalError.*\(.*\)' + message: 'Fatal error should not be used.' + severity: error + + enum_case_parameter: + name: 'Enum Case Parameter' + regex: 'case [a-zA-Z0-9]*\([a-zA-Z0-9\.<>?,\n\t =]+\)' + message: 'The associated values of an enum case should have parameters.' + severity: warning + + tab: + name: 'Whitespaces Instead of Tab' + regex: '\t' + message: 'Spaces should be used instead of tabs.' + severity: warning + + # Thanks to the creator of the SwiftLint rule + # "empty_first_line" + # https://github.com/coteditor/CotEditor/blob/main/.swiftlint.yml + # in the GitHub repository + # "CotEditor" + # https://github.com/coteditor/CotEditor + empty_first_line: + name: 'Empty First Line' + regex: '(^[ a-zA-Z ]*(?:protocol|extension|class|struct) (?!(?:var|let))[ a-zA-Z:]*\{\n *\S+)' + message: 'There should be an empty line after a declaration' + severity: error + +# Analyzer Rules +analyzer_rules: + - unused_declaration + - unused_import + +# Options +file_header: + required_pattern: '(// swift-tools-version: .+)?//\n// .*.swift\n// LevenshteinTransformations\n//\n// Created by .* on .*\.(\n// Edited by (.*,)+\.)*\n(\n// Thanks to .* for the .*:\n// ".*"\n// https://.* \(\d\d.\d\d.\d\d\))*//\n' +missing_docs: + warning: [internal, private] + error: [open, public] + excludes_extensions: false + excludes_inherited_types: false +type_contents_order: + order: + - case + - type_alias + - associated_type + - type_property + - instance_property + - ib_inspectable + - ib_outlet + - subscript + - initializer + - deinitializer + - subtype + - type_method + - view_life_cycle_method + - ib_action + - other_method diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9243a82 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,35 @@ +# Contributing + +Thank you very much for taking the time for contributing to this project. + +## Report a Bug +Just open a new issue on GitHub and describe the bug. It helps if your description is detailed. Thank you very much for your contribution! + +## Suggest a New Feature +Just open a new issue on GitHub and describe the idea. Thank you very much for your contribution! + +## Pull Requests +I am happy for every pull request, you do not have to follow these guidelines. However, it might help you to understand the project structure and make it easier for me to merge your pull request. Thank you very much for your contribution! + +### 1. Fork & Clone this Project +Start by clicking on the `Fork` button at the top of the page. Then, clone this repository to your computer. + +### 2. Open the Project +Open the project folder in GNOME Builder, Xcode or another IDE. + +### 3. Understand the Project Structure +- The `README.md` file contains a description of the app or package. +- The `Contributors.md` file contains the names or usernames of all the contributors with a link to their GitHub profile. +- The `LICENSE.md` contains a GPL-3.0 license. +- `CONTRIBUTING.md` is this file. +- Directory `data` that contains the icons. +- `Sources` contains the source code of the project. + +### 4. Edit the Code +Edit the code. If you add a new type, add documentation in the code. + +### 5. Commit to the Fork +Commit and push the fork. + +### 6. Pull Request +Open GitHub to submit a pull request. Thank you very much for your contribution! diff --git a/Contributors.md b/Contributors.md new file mode 100644 index 0000000..3cf3f03 --- /dev/null +++ b/Contributors.md @@ -0,0 +1,3 @@ +# Contributors + +- [david-swift](https://github.com/david-swift) diff --git a/Documentation/Reference/README.md b/Documentation/Reference/README.md new file mode 100644 index 0000000..3bb36d5 --- /dev/null +++ b/Documentation/Reference/README.md @@ -0,0 +1,18 @@ +# Reference Documentation + +## Structs + +- [Functions](structs/Functions.md) + +## Enums + +- [EditOperation](enums/EditOperation.md) +- [LevenshteinTransformations](enums/LevenshteinTransformations.md) +- [Transformation](enums/Transformation.md) + +## Extensions + +- [Array](extensions/Array.md) +- [String](extensions/String.md) + +This file was generated by [SourceDocs](https://github.com/eneko/SourceDocs) \ No newline at end of file diff --git a/Documentation/Reference/enums/EditOperation.md b/Documentation/Reference/enums/EditOperation.md new file mode 100644 index 0000000..5693115 --- /dev/null +++ b/Documentation/Reference/enums/EditOperation.md @@ -0,0 +1,23 @@ +**ENUM** + +# `EditOperation` + +An edit operation is a transformation without parameters. +Additionally, it has the case `noChange`. + +## Cases +### `noChange` + +No operation. + +### `replace` + +A replace operation. + +### `delete` + +A delete operation. + +### `insert` + +An insert operation. diff --git a/Documentation/Reference/enums/LevenshteinTransformations.md b/Documentation/Reference/enums/LevenshteinTransformations.md new file mode 100644 index 0000000..411f6de --- /dev/null +++ b/Documentation/Reference/enums/LevenshteinTransformations.md @@ -0,0 +1,32 @@ +**ENUM** + +# `LevenshteinTransformations` + +The enumeration holding the transformation functions. + +## Methods +### `levenshteinTransformations(from:to:)` + +The transformation function for arrays with equatable elements. +- Parameters: + - source: The original array. + - target: The target array. +- Returns: The required transformations. + +### `setOperations(_:editDistances:source:target:)` + +Set the operations and edit distances according to the source and target array. +- Parameters: + - operations: The operations. + - editDistances: The edit distances. + - source: The original array. + - target: The target array. +- Returns: The required transformations. + +### `levenshteinTransformations(from:to:)` + +The transformation function for arrays with identifiable elements. +- Parameters: + - source: The original array. + - target: The target array. +- Returns: The required transformations. diff --git a/Documentation/Reference/enums/Transformation.md b/Documentation/Reference/enums/Transformation.md new file mode 100644 index 0000000..3fee017 --- /dev/null +++ b/Documentation/Reference/enums/Transformation.md @@ -0,0 +1,46 @@ +**ENUM** + +# `Transformation` + +A transformation (replace, delete or insert). + +## Cases +### `replace(at:with:)` + +Replace the element at a certain index with a certain element. + +### `delete(at:)` + +Delete the element at a certain index. + +### `insert(at:element:)` + +Insert a certain element at a certain index. + +## Properties +### `index` + +The index at which is directly affected by the transformation. + +### `element` + +The element which is directly affected by the transformation. + +## Methods +### `description(source:)` + +A description of the transformation. +- Parameter source: The initial array. +- Returns: The description. + +### `log(source:)` + +Print a description of the transformation. +- Parameter source: The initial array. + +### `transform(functions:nextTransformations:)` + +Apply the transformation using a functions value. +- Parameters: + - functions: The functions value. + - nextTransformations: All the following transformations for modifying the indices. diff --git a/Documentation/Reference/extensions/Array.md b/Documentation/Reference/extensions/Array.md new file mode 100644 index 0000000..e2828c6 --- /dev/null +++ b/Documentation/Reference/extensions/Array.md @@ -0,0 +1,42 @@ +**EXTENSION** + +# `Array` + +## Methods +### `levenshteinDistance(to:)` + +Calculate the Levenshtein distance to another array. +- Parameter target: The target array. +- Returns: The Levenshtein distance. + +### `getTransformations(to:)` + +Get the transformations needed to transform the array into the target array. +- Parameter target: The target array. +- Returns: The transformations. + +### `transform(to:functions:)` + +Call every transformation step needed to transform the array into the target array. +- Parameters: + - target: The target array. + - functions: The transformation functions. + +### `identifiableLevenshteinDistance(to:)` + +Calculate the Levenshtein distance to another array. +- Parameter target: The target array. +- Returns: The Levenshtein distance. + +### `identifiableGetTransformations(to:)` + +Get the transformations needed to transform the array into the target array. +- Parameter target: The target array. +- Returns: The transformations. + +### `identifiableTransform(to:functions:)` + +Call every transformation step needed to transform the array into the target array. +- Parameters: + - target: The target array. + - functions: The transformation functions. diff --git a/Documentation/Reference/extensions/String.md b/Documentation/Reference/extensions/String.md new file mode 100644 index 0000000..9359b98 --- /dev/null +++ b/Documentation/Reference/extensions/String.md @@ -0,0 +1,23 @@ +**EXTENSION** + +# `String` + +## Methods +### `levenshteinDistance(to:)` + +Calculate the Levenshtein distance to another string. +- Parameter target: The target string. +- Returns: The Levenshtein distance. + +### `getTransformations(to:)` + +Get the transformations needed to transform the string into the target string. +- Parameter target: The target string. +- Returns: The transformations. + +### `transform(to:functions:)` + +Call every transformation step needed to transform the string into the target string. +- Parameters: + - target: The target string. + - functions: The transformation functions. diff --git a/Documentation/Reference/structs/Functions.md b/Documentation/Reference/structs/Functions.md new file mode 100644 index 0000000..badac35 --- /dev/null +++ b/Documentation/Reference/structs/Functions.md @@ -0,0 +1,27 @@ +**STRUCT** + +# `Functions` + +The replace, delete and insert functions type. + +## Properties +### `replace` + +The replace function. + +### `delete` + +The delete function. + +### `insert` + +The insert function. + +## Methods +### `init(replace:delete:insert:)` + +Initialize a functions value. +- Parameters: + - replace: Replace the element at a certain index with a certain element. + - delete: Delete the element at a certain index. + - insert: Insert a certain element at a certain index. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..626e124 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 david-swift + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e6d4dd2 --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +docs: + @sourcedocs generate --min-acl private -r --spm-module LevenshteinTransformations + +swiftlint: + @swiftlint --autocorrect diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..e28dbd0 --- /dev/null +++ b/Package.swift @@ -0,0 +1,30 @@ +// swift-tools-version: 5.8 +// +// Package.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +import PackageDescription + +/// The LevenshteinTransformations package. +let package = Package( + name: "LevenshteinTransformations", + products: [ + .library( + name: "LevenshteinTransformations", + targets: ["LevenshteinTransformations"] + ) + ], + targets: [ + .target( + name: "LevenshteinTransformations" + ), + .executableTarget( + name: "LevenshteinTransformationsTests", + dependencies: ["LevenshteinTransformations"], + path: "Tests" + ) + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..f14b739 --- /dev/null +++ b/README.md @@ -0,0 +1,96 @@ +

+ Levenshtein Transformations Icon +

Levenshtein Transformations

+

+ +

+ + GitHub + + ยท + + Contributor Docs + +

+ +Transform an array into any other array of the same type, or a string into any other string, using only the three transformations `replace`, `delete` and `insert`. + +## Table of Contents + +- [Installation](#Installation) +- [Usage](#Usage) +- [Thanks](#Thanks) + +## Installation + +1. Open your Swift package in GNOME Builder, Xcode, or any other IDE. +2. Open the `Package.swift` file. +3. Into the `Package` initializer, under `dependencies`, paste: +```swift +.package(url: "https://github.com/david-swift/LevenshteinTransformations", from: "0.1.0") +``` + +## Usage + +```swift +let source = [1, 2, 5, 6] +let target = [0, 1, 5, 6, 10] +``` + +There are three functions available for arrays containing elements conforming to `Equatable` and strings. + +### Arrays with `Equatable` Elements and Strings + +#### Levenshtein Distance +Get the Levenshtein distance with `levenshteinDistance(to:)`: +```swift +print(source.levenshteinDistance(to: target)) +``` +This example outputs `3`. + +#### Transformation Steps +Get the individual transformation steps with `getTransformations(to:)`. +```swift +print(source.getTransformations(to: target).map { $0.description(source: source) }.joined(separator: "\n")) +``` +This example prints the descriptions of the transformations: +``` +Replace '1' at position 0 with '0' +Replace '2' at position 1 with '1' +Insert '10' at position 4 +``` + +#### Run Functions for the Steps +Directly run functions for the `replace`, `delete` and `insert` transformations using the `transform(to:functions:)` function. +```swift +var modified = source + +source.transform( + to: target, + functions: .init { index, element in + modified[index] = element + } delete: { index in + modified.remove(at: index) + } insert: { index, element in + modified.insert(element, at: index) + } +) + +print(modified == target) +``` +This example outputs `true`. + +### Arrays with `Identifiable` Elements + +The same functions are available for arrays with identifiable elements, but they are named differently to avoid conflicts: +- `identifiableLevenshteinDistance(to:)` +- `identifiableGetTransformations(to:)` +- `identifiableTransform(to:functions:)` + +## Thanks + +- The [contributors](Contributors.md) +- [SwiftLint](https://github.com/realm/SwiftLint) for checking whether code style conventions are violated +- The programming language [Swift](https://github.com/apple/swift) +- [SourceDocs](https://github.com/SourceDocs/SourceDocs) used for generating the [docs](Documentation/Reference/README.md) + diff --git a/Sources/LevenshteinTransformations/EditOperation.swift b/Sources/LevenshteinTransformations/EditOperation.swift new file mode 100644 index 0000000..4439d3a --- /dev/null +++ b/Sources/LevenshteinTransformations/EditOperation.swift @@ -0,0 +1,21 @@ +// +// EditOperation.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +/// An edit operation is a transformation without parameters. +/// Additionally, it has the case `noChange`. +enum EditOperation { + + /// No operation. + case noChange + /// A replace operation. + case replace + /// A delete operation. + case delete + /// An insert operation. + case insert + +} diff --git a/Sources/LevenshteinTransformations/Extensions/Array.swift b/Sources/LevenshteinTransformations/Extensions/Array.swift new file mode 100644 index 0000000..99a56e7 --- /dev/null +++ b/Sources/LevenshteinTransformations/Extensions/Array.swift @@ -0,0 +1,68 @@ +// +// Array.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +extension Array where Element: Equatable { + + /// Calculate the Levenshtein distance to another array. + /// - Parameter target: The target array. + /// - Returns: The Levenshtein distance. + public func levenshteinDistance(to target: [Element]) -> Int { + getTransformations(to: target).count + } + + /// Get the transformations needed to transform the array into the target array. + /// - Parameter target: The target array. + /// - Returns: The transformations. + public func getTransformations(to target: [Element]) -> [Transformation] { + LevenshteinTransformations.levenshteinTransformations(from: self, to: target) + } + + /// Call every transformation step needed to transform the array into the target array. + /// - Parameters: + /// - target: The target array. + /// - functions: The transformation functions. + public func transform(to target: [Element], functions: Functions) { + var transformations = getTransformations(to: target) + + while !transformations.isEmpty { + let transformation = transformations.removeFirst() + transformation.transform(functions: functions, nextTransformations: &transformations) + } + } + +} + +extension Array where Element: Identifiable { + + /// Calculate the Levenshtein distance to another array. + /// - Parameter target: The target array. + /// - Returns: The Levenshtein distance. + public func identifiableLevenshteinDistance(to target: [Element]) -> Int { + identifiableGetTransformations(to: target).count + } + + /// Get the transformations needed to transform the array into the target array. + /// - Parameter target: The target array. + /// - Returns: The transformations. + public func identifiableGetTransformations(to target: [Element]) -> [Transformation] { + LevenshteinTransformations.levenshteinTransformations(from: self, to: target) + } + + /// Call every transformation step needed to transform the array into the target array. + /// - Parameters: + /// - target: The target array. + /// - functions: The transformation functions. + public func identifiableTransform(to target: [Element], functions: Functions) { + var transformations = identifiableGetTransformations(to: target) + + while !transformations.isEmpty { + let transformation = transformations.removeFirst() + transformation.transform(functions: functions, nextTransformations: &transformations) + } + } + +} diff --git a/Sources/LevenshteinTransformations/Extensions/String.swift b/Sources/LevenshteinTransformations/Extensions/String.swift new file mode 100644 index 0000000..da042e3 --- /dev/null +++ b/Sources/LevenshteinTransformations/Extensions/String.swift @@ -0,0 +1,37 @@ +// +// Array.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +extension String { + + /// Calculate the Levenshtein distance to another string. + /// - Parameter target: The target string. + /// - Returns: The Levenshtein distance. + public func levenshteinDistance(to target: String) -> Int { + getTransformations(to: target).count + } + + /// Get the transformations needed to transform the string into the target string. + /// - Parameter target: The target string. + /// - Returns: The transformations. + public func getTransformations(to target: String) -> [Transformation] { + Array(self).getTransformations(to: .init(target)) + } + + /// Call every transformation step needed to transform the string into the target string. + /// - Parameters: + /// - target: The target string. + /// - functions: The transformation functions. + public func transform(to target: String, functions: Functions) { + var transformations = getTransformations(to: target) + + while !transformations.isEmpty { + let transformation = transformations.removeFirst() + transformation.transform(functions: functions, nextTransformations: &transformations) + } + } + +} diff --git a/Sources/LevenshteinTransformations/Functions.swift b/Sources/LevenshteinTransformations/Functions.swift new file mode 100644 index 0000000..18dc7b5 --- /dev/null +++ b/Sources/LevenshteinTransformations/Functions.swift @@ -0,0 +1,33 @@ +// +// Functions.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +/// The replace, delete and insert functions type. +public struct Functions { + + /// The replace function. + var replace: (Int, Element) -> Void + /// The delete function. + var delete: (Int) -> Void + /// The insert function. + var insert: (Int, Element) -> Void + + /// Initialize a functions value. + /// - Parameters: + /// - replace: Replace the element at a certain index with a certain element. + /// - delete: Delete the element at a certain index. + /// - insert: Insert a certain element at a certain index. + public init( + replace: @escaping (Int, Element) -> Void, + delete: @escaping (Int) -> Void, + insert: @escaping (Int, Element) -> Void + ) { + self.replace = replace + self.delete = delete + self.insert = insert + } + +} diff --git a/Sources/LevenshteinTransformations/LevenshteinTransformations.swift b/Sources/LevenshteinTransformations/LevenshteinTransformations.swift new file mode 100644 index 0000000..9aaf380 --- /dev/null +++ b/Sources/LevenshteinTransformations/LevenshteinTransformations.swift @@ -0,0 +1,138 @@ +// +// LevenshteinTransformations.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +/// The enumeration holding the transformation functions. +enum LevenshteinTransformations { + + /// The transformation function for arrays with equatable elements. + /// - Parameters: + /// - source: The original array. + /// - target: The target array. + /// - Returns: The required transformations. + static func levenshteinTransformations( + from source: [Element], + to target: [Element] + ) -> [Transformation] where Element: Equatable { + let sourceCount = source.count + let targetCount = target.count + + var editDistances = Array(repeating: Array(repeating: 0, count: targetCount + 1), count: sourceCount + 1) + var operations: [[EditOperation]] = .init( + repeating: .init(repeating: .noChange, count: targetCount + 1), + count: sourceCount + 1 + ) + + setOperations(&operations, editDistances: &editDistances, source: source, target: target) + + var transformations: [Transformation] = [] + var indexSource = sourceCount + var indexTarget = targetCount + + while indexSource > 0 || indexTarget > 0 { + switch operations[indexSource][indexTarget] { + case .noChange: + indexSource -= 1 + indexTarget -= 1 + case .replace: + transformations.append(.replace(at: indexSource - 1, with: target[indexTarget - 1])) + indexSource -= 1 + indexTarget -= 1 + case .delete: + transformations.append(.delete(at: indexSource - 1)) + indexSource -= 1 + case .insert: + transformations.append(.insert(at: indexSource, element: target[indexTarget - 1])) + indexTarget -= 1 + } + } + + transformations.reverse() + return transformations + } + + /// Set the operations and edit distances according to the source and target array. + /// - Parameters: + /// - operations: The operations. + /// - editDistances: The edit distances. + /// - source: The original array. + /// - target: The target array. + /// - Returns: The required transformations. + static func setOperations( + _ operations: inout [[EditOperation]], + editDistances: inout [[Int]], + source: [Element], + target: [Element] + ) where Element: Equatable { + let sourceCount = source.count + let targetCount = target.count + + for sourceIndex in 0...sourceCount { + editDistances[sourceIndex][0] = sourceIndex + operations[sourceIndex][0] = .delete + } + + for targetIndex in 0...targetCount { + editDistances[0][targetIndex] = targetIndex + operations[0][targetIndex] = .insert + } + + for sourceIndex in 1...sourceCount { + for targetIndex in 1...targetCount { + if source[sourceIndex - 1] == target[targetIndex - 1] { + editDistances[sourceIndex][targetIndex] = editDistances[sourceIndex - 1][targetIndex - 1] + operations[sourceIndex][targetIndex] = .noChange + } else { + editDistances[sourceIndex][targetIndex] = 1 + min( + editDistances[sourceIndex - 1][targetIndex - 1], + editDistances[sourceIndex - 1][targetIndex], + editDistances[sourceIndex][targetIndex - 1] + ) + if editDistances[sourceIndex][targetIndex] == editDistances[sourceIndex - 1][targetIndex - 1] + 1 { + operations[sourceIndex][targetIndex] = .replace + } else if editDistances[sourceIndex][targetIndex] + == editDistances[sourceIndex - 1][targetIndex] + 1 { + operations[sourceIndex][targetIndex] = .delete + } else { + operations[sourceIndex][targetIndex] = .insert + } + } + } + } + } + + /// The transformation function for arrays with identifiable elements. + /// - Parameters: + /// - source: The original array. + /// - target: The target array. + /// - Returns: The required transformations. + static func levenshteinTransformations( + from source: [Element], + to target: [Element] + ) -> [Transformation] where Element: Identifiable { + let transformations = levenshteinTransformations(from: source.map { $0.id }, to: target.map { $0.id }) + return transformations.compactMap { transformation in + if let element = target.first(where: { $0.id == transformation.element }) { + switch transformation { + case let .replace(index, _): + return .replace(at: index, with: element) + case let .insert(index, _): + return .insert(at: index, element: element) + default: + return nil + } + } else { + switch transformation { + case let .delete(index): + return .delete(at: index) + default: + return nil + } + } + } + } + +} diff --git a/Sources/LevenshteinTransformations/Transformation.swift b/Sources/LevenshteinTransformations/Transformation.swift new file mode 100644 index 0000000..a9b17e9 --- /dev/null +++ b/Sources/LevenshteinTransformations/Transformation.swift @@ -0,0 +1,106 @@ +// +// Transformation.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +// swiftlint:disable identifier_name + +/// A transformation (replace, delete or insert). +public enum Transformation { + + /// Replace the element at a certain index with a certain element. + case replace(at: Int, with: Element) + /// Delete the element at a certain index. + case delete(at: Int) + /// Insert a certain element at a certain index. + case insert(at: Int, element: Element) + + /// The index at which is directly affected by the transformation. + public var index: Int { + get { + switch self { + case let .replace(index, _), let .delete(index), let .insert(index, _): + return index + } + } + set { + switch self { + case let .replace(_, element): + self = .replace(at: newValue, with: element) + case .delete: + self = .delete(at: newValue) + case let .insert(_, element): + self = .insert(at: newValue, element: element) + } + } + } + + /// The element which is directly affected by the transformation. + public var element: Element? { + get { + switch self { + case let .replace(_, element), let .insert(_, element): + return element + case .delete: + return nil + } + } + set { + if let newValue { + switch self { + case let .replace(index, _): + self = .replace(at: index, with: newValue) + case let .insert(index, _): + self = .insert(at: index, element: newValue) + case .delete: + break + } + } + } + } + + /// A description of the transformation. + /// - Parameter source: The initial array. + /// - Returns: The description. + public func description(source: [Element]) -> String { + switch self { + case let .replace(index, element): + return "Replace '\(source[index])' at position \(index) with '\(element)'" + case let .delete(index): + return "Delete '\(source[index])' at position \(index)" + case let .insert(index, element): + return "Insert '\(element)' at position \(index)" + } + } + + /// Print a description of the transformation. + /// - Parameter source: The initial array. + public func log(source: [Element]) { + print(description(source: source)) + } + + /// Apply the transformation using a functions value. + /// - Parameters: + /// - functions: The functions value. + /// - nextTransformations: All the following transformations for modifying the indices. + public func transform(functions: Functions, nextTransformations: inout [Transformation]) { + switch self { + case let .replace(index, element): + functions.replace(index, element) + case let .delete(index): + functions.delete(index) + for index in nextTransformations.indices { + nextTransformations[index].index -= 1 + } + case let .insert(index, element): + functions.insert(index, element) + for index in nextTransformations.indices { + nextTransformations[index].index += 1 + } + } + } +} + +// swiftlint:enable identifier_name diff --git a/Tests/LevenshteinTransformationsTests.swift b/Tests/LevenshteinTransformationsTests.swift new file mode 100644 index 0000000..ff70abc --- /dev/null +++ b/Tests/LevenshteinTransformationsTests.swift @@ -0,0 +1,96 @@ +// +// LevenshteinTransformationsTests.swift +// LevenshteinTransformations +// +// Created by david-swift on 01.01.24. +// + +// swiftlint:disable no_magic_numbers + +import LevenshteinTransformations + +/// Tests for the LevenshteinTransformations library. +@main +enum LevenshteinTransformationsTests { + + /// An example type conforming to `Identifiable`. + struct TestType: Identifiable, Equatable { + + /// The identifier. + var id: Int + + } + + /// Test the `transform` function on an equatable array. + static func testEquatable() { + let source = [1, 2, 5, 6] + let target = [0, 1, 5, 6, 10] + + var modified = source + + source.transform( + to: target, + functions: .init { index, element in + modified[index] = element + } delete: { index in + modified.remove(at: index) + } insert: { index, element in + modified.insert(element, at: index) + } + ) + + print(modified == target) + } + + /// Test the `transform` function on an identifiable array. + static func testIdentifiable() { + let source = [1, 2, 5, 6].map { TestType(id: $0) } + let target = [0, 1, 5, 6, 10].map { TestType(id: $0) } + + var modified = source + + source.identifiableTransform( + to: target, + functions: .init { index, element in + modified[index] = element + } delete: { index in + modified.remove(at: index) + } insert: { index, element in + modified.insert(element, at: index) + } + ) + + print(modified == target) + } + + /// Test the `transform` function on a string. + static func testString() { + let source = "Hello World" + let target = "Servus Welt" + + var modified = Array(source) + + source.transform( + to: target, + functions: .init { index, element in + modified[index] = element + } delete: { index in + modified.remove(at: index) + } insert: { index, element in + modified.insert(element, at: index) + } + ) + + print(String(modified) == target) + } + + /// Run the tests. + static func main() { + testEquatable() + testIdentifiable() + testString() + } + +} + +// swiftlint:enable no_magic_numbers diff --git a/data/Icon.svg b/data/Icon.svg new file mode 100644 index 0000000..a801c41 --- /dev/null +++ b/data/Icon.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + +