Skip to content

Commit

Permalink
Try to fit into grid with fewerlines first and return early
Browse files Browse the repository at this point in the history
  • Loading branch information
ariasuni committed Dec 26, 2021
1 parent de48112 commit 19f094b
Showing 1 changed file with 3 additions and 44 deletions.
47 changes: 3 additions & 44 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,34 +322,6 @@ impl Grid {
Dimensions { num_lines, widths }
}

fn theoretical_max_num_lines(&self, maximum_width: usize) -> usize {
// TODO: Make code readable / efficient.
let mut theoretical_min_num_cols = 0;
let mut col_total_width_so_far = 0;

let mut cells = self.cells.clone();
cells.sort_unstable_by(|a, b| b.width.cmp(&a.width)); // Sort in reverse order

for cell in &cells {
if cell.width + col_total_width_so_far <= maximum_width {
theoretical_min_num_cols += 1;
col_total_width_so_far += cell.width;
} else {
let mut theoretical_max_num_lines = self.cell_count / theoretical_min_num_cols;
if self.cell_count % theoretical_min_num_cols != 0 {
theoretical_max_num_lines += 1;
}
return theoretical_max_num_lines;
}
col_total_width_so_far += self.options.filling.width()
}

// If we make it to this point, we have exhausted all cells before
// reaching the maximum width; the theoretical max number of lines
// needed to display all cells is 1.
1
}

fn width_dimensions(&self, maximum_width: Width) -> Option<Dimensions> {
if self.widest_cell_length > maximum_width {
// Largest cell is wider than maximum width; it is impossible to fit.
Expand All @@ -370,22 +342,9 @@ impl Grid {
return None;
}

let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width);
if theoretical_max_num_lines == 1 {
// This if—statement is neccesary for the function to work correctly
// for small inputs.
return Some(Dimensions {
num_lines: 1,
// I clone self.cells twice. Once here, and once in
// self.theoretical_max_num_lines. Perhaps not the best for
// performance?
widths: self.cells.clone().into_iter().map(|cell| cell.width).collect()
});
}
// Instead of numbers of columns, try to find the fewest number of *lines*
// that the output will fit in.
let mut smallest_dimensions_yet = None;
for num_lines in (1 ..= theoretical_max_num_lines).rev() {
for num_lines in 1..=self.cell_count {
// The number of columns is the number of cells divided by the number
// of lines, *rounded up*.
let num_columns = if self.cell_count % num_lines == 0 {
Expand All @@ -410,13 +369,13 @@ impl Grid {

let potential_dimensions = self.column_widths(num_lines, num_columns);
if potential_dimensions.widths.iter().sum::<Width>() < adjusted_width {
smallest_dimensions_yet = Some(potential_dimensions);
return Some(potential_dimensions);
} else {
continue;
}
}

smallest_dimensions_yet
None
}
}

Expand Down

0 comments on commit 19f094b

Please sign in to comment.