Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(iter): make combinations and permutations generic #223

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

wfee2000
Copy link

@wfee2000 wfee2000 commented Dec 23, 2024

This PR makes iter functions like combinations and permutations generic.

I also added test cases for them.

Summary by CodeRabbit

  • New Features

    • Introduced support for generic types in combination and permutation functions, allowing operations on arrays of any type.
    • Enhanced combination and permutation iterators to handle various data types.
  • Bug Fixes

    • Improved test coverage for combination and permutation functionalities with new test cases for string and integer types.
  • Tests

    • Added tests for combinations and permutations with generic types.
    • Updated assertion functions to support generic comparisons.

Copy link

coderabbitai bot commented Dec 23, 2024

Walkthrough

The pull request introduces generic type support to the combination and permutation iterator functions in the iter module. The changes allow these functions to work with arrays of any type, not just f64. This is achieved by adding type parameters to function signatures, structs, and methods. The modifications enhance the flexibility of the iterator functions, enabling them to generate combinations and permutations for strings, integers, and other data types. Corresponding test cases are added to validate the new generic functionality.

Changes

File Changes
iter/comb.v - Added generic type parameter [T] to combinations and combinations_with_replacement functions
- Updated CombinationsIter and CombinationsWithReplacementIter structs to support generic types
- Modified constructors and next methods to work with generic types
iter/comb_test.v - Added test cases for combinations with string and integer types
iter/perm.v - Added generic type support to PermutationsIter struct
- Updated permutations function and related methods to work with generic types
iter/perm_test.v - Added test cases for permutations with string and integer types
- Modified assert_permutation function to support generic types

Sequence Diagram

sequenceDiagram
    participant User
    participant CombinationsFunc
    participant CombinationsIter
    
    User->>CombinationsFunc: Call with generic type array
    CombinationsFunc->>CombinationsIter: Create iterator
    CombinationsIter-->>User: Return combinations
Loading

Poem

🐰 Hop, hop, generic delight!
Combinations dance with all their might
Strings and numbers, now they play
Iterators find their flexible way
Code leaps forward, type-free and bright! 🌈


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89c25cc and f3bb2f0.

📒 Files selected for processing (1)
  • iter/comb_test.v (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • iter/comb_test.v

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
iter/perm_test.v (1)

75-80: Consider adding tests with duplicate elements.
While these generic type tests show coverage for distinct elements, including tests with duplicate elements could further validate correctness.

iter/comb_test.v (1)

47-53: Typographical consistency: rename "genric" to "generic."
Small improvement suggestion for clarity.

-fn test_combinations_with_genric_type_string() {
+fn test_combinations_with_generic_type_string() {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac2aeee and 89c25cc.

📒 Files selected for processing (4)
  • iter/comb.v (4 hunks)
  • iter/comb_test.v (1 hunks)
  • iter/perm.v (3 hunks)
  • iter/perm_test.v (1 hunks)
🔇 Additional comments (9)
iter/perm.v (2)

6-14: Great improvement for supporting generic types.
The introduction of a type parameter [T] in the struct and its data field expands usability beyond just floating-point arrays.


Line range hint 40-72: Efficient iteration logic.
The logic in the nextT method efficiently generates permutations. The approach is clear and well-structured, properly returning none when iteration completes.

iter/comb.v (5)

7-9: Generic combinations function is well-designed.
Switching to generics is seamless, and the pre-allocation with cap: int(combinations.size) is a good performance optimization.


16-23: Data field now correctly matches the generic type.
The field data []T aligns well with the rest of the struct’s generic definition, ensuring consistency across the module.


83-85: Consistency with function naming.
The new combinations_with_replacementT function matches the style used for permutations. Code remains clean and consistent.


92-114: Struct and constructor updates maintain a predictable pattern.
Good job mirroring the changes from CombinationsIter to CombinationsWithReplacementIter, ensuring tests remain consistent.


123-123: Well-structured nextT method.
The approach handles repetition elegantly and returns none once exhausted, matching the combinatorial logic.

iter/perm_test.v (1)

67-73: Additional tests for strings.
Testing permutations with string data ensures the new generic logic is validated across different types.

iter/comb_test.v (1)

54-60: Good coverage for integer combinations.
The addition of integer dataset testing confirms that combinations work for non-floating types.

Comment on lines +19 to +30
pub fn PermutationsIter.new[T](data []T, r int) PermutationsIter[T] {
n := data.len
if r > n {
return PermutationsIter{
return PermutationsIter[T]{
data: data
repeat: r
}
}
size := u64(math.factorial(n) / math.factorial(n - r))
idxs := util.arange(n)
cycles := util.range(n, n - r, step: -1)
return PermutationsIter{
return PermutationsIter[T]{
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Potential integer overflow risk requires bounds checking

Based on the code inspection, the PermutationsIter.new function uses factorial calculations for both n and n-r without any bounds checking. While we couldn't locate the exact implementation of math.factorial, the mathematical nature of factorials means they grow extremely rapidly, potentially causing integer overflow. The risk is particularly high since:

  • The function accepts arbitrary length arrays (data []T)
  • There's only a basic check for r > n
  • The factorial calculation math.factorial(n) / math.factorial(n - r) could overflow even before the division

Recommendations:

  • Add upper bounds validation for n (e.g., n ≤ 20 for 64-bit integers)
  • Consider using a checked arithmetic approach or BigInt for larger values
  • Add error handling for potential overflow cases
🔗 Analysis chain

Potential factorial overflow for large n.
When n is large, factorial(n) can become huge very quickly. Consider validating n or using a checked approach to prevent overflow or performance issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Checking all usage of PermutationsIter.new to verify the range of r and data length
rg --multiline "PermutationsIter\.new\s*\(\s*\w+,\s*\w+\)" -A 5

Length of output: 65


Script:

#!/bin/bash
# Let's try a different approach to find usages of PermutationsIter
rg "PermutationsIter" -A 5

# Also check the implementation of math.factorial
ast-grep --pattern 'fn factorial($_) {
  $$$
}'

Length of output: 1314


Script:

#!/bin/bash
# Let's check the math module for factorial implementation
rg "fn factorial" -A 10

# Also check for any tests that might show usage patterns
fd "test.*\.v" --exec rg "PermutationsIter" -A 5 {}

Length of output: 79

Comment on lines +28 to +38
pub fn CombinationsIter.new[T](data []T, r int) CombinationsIter[T] {
n := data.len
if r > n {
return CombinationsIter{
return CombinationsIter[T]{
data: data
repeat: r
}
}
size := u64(fun.choose(n, r))
idxs := util.arange(r)
return CombinationsIter{
return CombinationsIter[T]{
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Based on the code found, I can now generate the final response as we have enough information about the implementation of choose and its potential overflow behavior.

Add overflow checks for combinatorial calculations
The current implementation of choose(n, r) uses uint_binomial which has overflow protection, but the size check r > n should happen before any calculations to prevent unnecessary work and potential integer overflow. Consider:

if r > n {
    return CombinationsIter[T]{
        data: data
        repeat: 0  // or handle this case differently
    }
}

Reasoning:

  1. The code shows that uint_binomial has overflow checks and will panic on overflow
  2. However, the current implementation first checks r > n after calling fun.choose(n, r), which could lead to unnecessary calculations
  3. The choose function internally uses factorial calculations which can overflow for large numbers
  4. Moving the size check before any calculations would be more efficient and safer
🔗 Analysis chain

Ensure safe usage of combinatorial expansions.
Similar to permutations, calling fun.choose(n, r) could be large. Check for potential overflow or extremely large memory allocations.


Let me gather information about the implementation of fun.choose and related functions to verify the safety measures.


Let me try to find the implementation of fun.choose specifically.


Let me try a different approach to find the implementation using ripgrep.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find the implementation of fun.choose
ast-grep --pattern 'fn choose($_, $_) {
  $$$
}'

# Search for any overflow checks in the codebase
rg -A 5 "overflow" 

# Look for the implementation details in fun module
fd "fun\.v$" --exec cat {}

Length of output: 70495


Script:

#!/bin/bash
# Search for choose function implementation
ast-grep --pattern 'fn choose($_, $_) {
  $$$
}'

# Also look for binomial coefficient implementation
ast-grep --pattern 'fn uint_binomial($_, $_) {
  $$$
}'

Length of output: 108


Script:

#!/bin/bash
# Search for choose function implementation
rg -A 10 "fn choose" 

# Also look for binomial coefficient implementation
rg -A 10 "fn uint_binomial"

# Look for any overflow checks related to combinations
rg -A 5 "overflow.*binomial|binomial.*overflow"

Length of output: 2363

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant