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 initial threashold for k!=10,100,1000 #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

amallia
Copy link
Member

@amallia amallia commented Oct 24, 2024

Initial threashold is not set correctly is k is not 10,100 or 1000

@JMMackenzie
Copy link
Member

This looks fine, but would it be preferable to use the next highest score if one exists?

For example, a user wants $k = 50$ - can't we use the 100 threshold?

}
}

pub fn kth(&self, k: usize) -> u8 {
return self.kth_score[Self::map_kth_value(k)];
if let Some(v) = Self::map_kth_value(k) {
Copy link
Member

Choose a reason for hiding this comment

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

Could be:

Self::map_kth_value(k).map(|idx| self.kth_score[idx]).unwrap_or(0)

But to @JMMackenzie's point, I think he means something like this:

pub fn kth(&self, k: usize) -> u8 {
    if k <= 1000 {
        self.kth_score[(k - 1).ilog10()]
    } else {
        0
    }
}

Notice I used log to make it succinct, but I would encourage you to benchmark if this makes sense.

Either way, even if you are using match/if, I wouldn't use map_kth_value, just straight up use a match statement and put self.kth_score[...] in each branch. The reason is that you'll need to do another check for Option, and then range check for array access. If anything, I would use self.kth_score.get(map_kth_value(k)).unwrap_or(0) and let the result of the inner func go out of range. This way, you should be able to only have one check, I think.

In fact, the function I suggested above could be:

pub fn kth(&self, k: usize) -> u8 {
    self.kth_score.get((k - 1).ilog10()).unwrap_or(0)
}

Though now you must calculate log first, even for large k. But if this is not an issue, you can hardly beat the simplicity of a one-liner ;)

Copy link
Member

Choose a reason for hiding this comment

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

Or how about this crazy idea:

pub fn kth(&self, k: usize) -> u8 {
    let idx = ((n > 10) as usize)
        + (n > 100) as usize
        + (n > 1000) as usize;
    self.kth_score.get(idx).unwrap_or(0)
}

Copy link
Member

Choose a reason for hiding this comment

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

That's beautiful 😍

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.

3 participants