How to calculate number of columns such that every row has either all even or all odd numbers of items, in compact a way as possible?

I would like to layout unicode glyphs similar to this:

There could be anywhere from 13 to say 100 items in the displayed collection (alphabets, abjads, abugidas, syllabaries, etc..), so could have a set with 99 items, or one with 16 items, etc..

How can you most beautiful (and automatically) layout the elements (so that it is also nice when responsive)? Here is what I have by default with flexbox:

Each item has a fixed height, and the width is responsive (but the same for each element).

The goal is to have every row have either an even number, or an odd number, of items. This way all vertical columns will line up (and it won’t do what my animated gif is doing, where even/odd rows are intermingled).

  1. Is it possible to do some math formula to calculate something like “you need to 5 items per row, except the last row will have 3 (or 1)”? Given some total count like 99?

How would you maybe do that?

I have a React component which does the Flexbox layout like <Grid minWidth={96} gap={8} maxColumns={5} breakpoints={[5, 3, 1]} />, where breakpoints are the number of items allowed per row, and maxColumns is the max columns (breakpoints/maxColumn is kinda redundant, you can define either or, maybe I’ll clean that up later). All this info might be irrelevant, but just pointing out just in case, it’s my responsive grid component.

How can I somehow divide my total by x to figure out if it should be even or odd rows, and then set the maxColumns or breakpoints to whatever will be “most compact”? So for example:

  • If it’s 26 elements, it would look best as 6 rows of 4, followed by 1 row of 2. – If it’s 27 elements,

The “beauty” of it might be subjective, and there’s not a clear rule for what is most beautiful. Just looking for anything that doesn’t easliy leave an orphaned single node at the end and then have 7 items on all other rows. Ideally we have:

  • Between 3 and 7 columns.
  • Last row must have the same number of items in all previous rows, or no less than maxRowCount - 2 (so if all rows have 7, the last row can have 5 or 7 only, or if all rows have 5, then the last row can have 3 or 5 only, etc.).
  • Row item has a minWidth: 96px, and grows to fill the space. I can figure out how to make things responsive once we get the basics of this working, but assume a containerWidth exists.

So in my head, say we have containerWidth === 700px. Then, 700/96 == 7+, so perhaps 7 per row. If we have 99 items (for example), then 99 % 7 == 1, so 7 won’t work because we’ll have 1 in the last row. 6 won’t work because 99 is even, so try 5? 99 % 5 == 4, that won’t work because 4 is even. So try 3, 99 % 3 == 0, so that would work as is, use that!

How would you implement something like that?

Here is an example that repeatedly tests if the number of columns matches your criteria

const ranges = [ 
  [0x2600, 0x26FF], // Symbols
  [0x2700, 0x27BF], // Dingbats
  [0x1F300, 0x1F5FF] // Symbols and Pictographs
];

const randomUnicodeGlyph = () => {
  const range = ranges[Math.floor(Math.random() * ranges.length)];
  const codePoint = Math.floor(range[0] + Math.random() * (range[1] - range[0] + 1));
  return String.fromCodePoint(codePoint);
};

// Generate a set of random Unicode glyphs
const generateGlyphSet = (length) => Array.from({ length }, randomUnicodeGlyph);

// Calculate the best number of columns per row
const calculateColumns = (totalItems, minItemWidth, containerWidth) => {
  const minColumns = 3;
  const maxColumns = 7;
  let possibleColumns = Math.min(Math.floor(containerWidth / minItemWidth), maxColumns);

  for (let columns = possibleColumns; columns >= minColumns; columns--) {
    let rows = Math.floor(totalItems / columns);
    let lastRowItems = totalItems % columns;

    if (lastRowItems === 0 || lastRowItems >= (columns - 2)) {
      return columns;
    }
  }
  return minColumns; // fallback
};

// HTML table for the glyph set
const createTable = (glyphSet, containerWidth, minItemWidth) => {
  const columns = calculateColumns(glyphSet.length, minItemWidth, containerWidth);
  return `
      <table class="glyph-table">
        <tr>${glyphSet.map((glyph, index) => 
          `<td>${glyph}</td>${(index + 1) % columns === 0 && (index + 1 !== glyphSet.length) ? '</tr><tr>' : ''}`
        ).join('')}
        </tr>
      </table><hr/>`;
};

// Generate three sets of glyphs with random lengths between 13 and 100
const sets = [
  generateGlyphSet(16),
  generateGlyphSet(26),
  generateGlyphSet(99)
];

const containerWidth = 700;
const minItemWidth = 96;
document.body.innerHTML = sets.map(set => createTable(set, containerWidth, minItemWidth)).join('');
.glyph-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.glyph-table td {
  height: 96px;
  text-align: center;
  font-size: 24px;
  padding: 3px;
}

Something like this seems correct, but did I solve it properly?

console.log(
  99,
  calculateColumns({ totalCount: 99, itemWidth: 96, containerWidth: 700 })
);
console.log(
  98,
  calculateColumns({ totalCount: 98, itemWidth: 96, containerWidth: 700 })
);
console.log(
  97,
  calculateColumns({ totalCount: 97, itemWidth: 96, containerWidth: 700 })
);
console.log(
  96,
  calculateColumns({ totalCount: 96, itemWidth: 96, containerWidth: 700 })
);
console.log(
  95,
  calculateColumns({ totalCount: 95, itemWidth: 96, containerWidth: 700 })
);
console.log(
  94,
  calculateColumns({ totalCount: 94, itemWidth: 96, containerWidth: 700 })
);
console.log(
  93,
  calculateColumns({ totalCount: 93, itemWidth: 96, containerWidth: 700 })
);
console.log(
  91,
  calculateColumns({ totalCount: 91, itemWidth: 96, containerWidth: 700 })
);

function calculateColumns({ totalCount, itemWidth, containerWidth }) {
  let max = Math.min(Math.floor(containerWidth / itemWidth), 7)
  while (max > 3) {
    const maxIsEven = isEven(max)
    const remainder = totalCount % max
    const remainderIsEven = isEven(remainder)
    if (maxIsEven && remainderIsEven) {
      const diff = max - remainder
      if (diff <= 2) {
        return max
      }
    } else if (!maxIsEven && (!remainderIsEven || !remainder)) {
      const diff = max - remainder
      if (diff <= 2) {
        return max;
      }
    } else {
      // one is even, one is odd
    }
    max--
  }
  return max
}

function isEven(n) {
  return n % 2 === 0
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to calculate number of columns such that every row has either all even or all odd numbers of items, in compact a way as possible?

I would like to layout unicode glyphs similar to this:

There could be anywhere from 13 to say 100 items in the displayed collection (alphabets, abjads, abugidas, syllabaries, etc..), so could have a set with 99 items, or one with 16 items, etc..

How can you most beautiful (and automatically) layout the elements (so that it is also nice when responsive)? Here is what I have by default with flexbox:

Each item has a fixed height, and the width is responsive (but the same for each element).

The goal is to have every row have either an even number, or an odd number, of items. This way all vertical columns will line up (and it won’t do what my animated gif is doing, where even/odd rows are intermingled).

  1. Is it possible to do some math formula to calculate something like “you need to 5 items per row, except the last row will have 3 (or 1)”? Given some total count like 99?

How would you maybe do that?

I have a React component which does the Flexbox layout like <Grid minWidth={96} gap={8} maxColumns={5} breakpoints={[5, 3, 1]} />, where breakpoints are the number of items allowed per row, and maxColumns is the max columns (breakpoints/maxColumn is kinda redundant, you can define either or, maybe I’ll clean that up later). All this info might be irrelevant, but just pointing out just in case, it’s my responsive grid component.

How can I somehow divide my total by x to figure out if it should be even or odd rows, and then set the maxColumns or breakpoints to whatever will be “most compact”? So for example:

  • If it’s 26 elements, it would look best as 6 rows of 4, followed by 1 row of 2. – If it’s 27 elements,

The “beauty” of it might be subjective, and there’s not a clear rule for what is most beautiful. Just looking for anything that doesn’t easliy leave an orphaned single node at the end and then have 7 items on all other rows. Ideally we have:

  • Between 3 and 7 columns.
  • Last row must have the same number of items in all previous rows, or no less than maxRowCount - 2 (so if all rows have 7, the last row can have 5 or 7 only, or if all rows have 5, then the last row can have 3 or 5 only, etc.).
  • Row item has a minWidth: 96px, and grows to fill the space. I can figure out how to make things responsive once we get the basics of this working, but assume a containerWidth exists.

So in my head, say we have containerWidth === 700px. Then, 700/96 == 7+, so perhaps 7 per row. If we have 99 items (for example), then 99 % 7 == 1, so 7 won’t work because we’ll have 1 in the last row. 6 won’t work because 99 is even, so try 5? 99 % 5 == 4, that won’t work because 4 is even. So try 3, 99 % 3 == 0, so that would work as is, use that!

How would you implement something like that?

Here is an example that repeatedly tests if the number of columns matches your criteria

const ranges = [ 
  [0x2600, 0x26FF], // Symbols
  [0x2700, 0x27BF], // Dingbats
  [0x1F300, 0x1F5FF] // Symbols and Pictographs
];

const randomUnicodeGlyph = () => {
  const range = ranges[Math.floor(Math.random() * ranges.length)];
  const codePoint = Math.floor(range[0] + Math.random() * (range[1] - range[0] + 1));
  return String.fromCodePoint(codePoint);
};

// Generate a set of random Unicode glyphs
const generateGlyphSet = (length) => Array.from({ length }, randomUnicodeGlyph);

// Calculate the best number of columns per row
const calculateColumns = (totalItems, minItemWidth, containerWidth) => {
  const minColumns = 3;
  const maxColumns = 7;
  let possibleColumns = Math.min(Math.floor(containerWidth / minItemWidth), maxColumns);

  for (let columns = possibleColumns; columns >= minColumns; columns--) {
    let rows = Math.floor(totalItems / columns);
    let lastRowItems = totalItems % columns;

    if (lastRowItems === 0 || lastRowItems >= (columns - 2)) {
      return columns;
    }
  }
  return minColumns; // fallback
};

// HTML table for the glyph set
const createTable = (glyphSet, containerWidth, minItemWidth) => {
  const columns = calculateColumns(glyphSet.length, minItemWidth, containerWidth);
  return `
      <table class="glyph-table">
        <tr>${glyphSet.map((glyph, index) => 
          `<td>${glyph}</td>${(index + 1) % columns === 0 && (index + 1 !== glyphSet.length) ? '</tr><tr>' : ''}`
        ).join('')}
        </tr>
      </table><hr/>`;
};

// Generate three sets of glyphs with random lengths between 13 and 100
const sets = [
  generateGlyphSet(16),
  generateGlyphSet(26),
  generateGlyphSet(99)
];

const containerWidth = 700;
const minItemWidth = 96;
document.body.innerHTML = sets.map(set => createTable(set, containerWidth, minItemWidth)).join('');
.glyph-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.glyph-table td {
  height: 96px;
  text-align: center;
  font-size: 24px;
  padding: 3px;
}

Something like this seems correct, but did I solve it properly?

console.log(
  99,
  calculateColumns({ totalCount: 99, itemWidth: 96, containerWidth: 700 })
);
console.log(
  98,
  calculateColumns({ totalCount: 98, itemWidth: 96, containerWidth: 700 })
);
console.log(
  97,
  calculateColumns({ totalCount: 97, itemWidth: 96, containerWidth: 700 })
);
console.log(
  96,
  calculateColumns({ totalCount: 96, itemWidth: 96, containerWidth: 700 })
);
console.log(
  95,
  calculateColumns({ totalCount: 95, itemWidth: 96, containerWidth: 700 })
);
console.log(
  94,
  calculateColumns({ totalCount: 94, itemWidth: 96, containerWidth: 700 })
);
console.log(
  93,
  calculateColumns({ totalCount: 93, itemWidth: 96, containerWidth: 700 })
);
console.log(
  91,
  calculateColumns({ totalCount: 91, itemWidth: 96, containerWidth: 700 })
);

function calculateColumns({ totalCount, itemWidth, containerWidth }) {
  let max = Math.min(Math.floor(containerWidth / itemWidth), 7)
  while (max > 3) {
    const maxIsEven = isEven(max)
    const remainder = totalCount % max
    const remainderIsEven = isEven(remainder)
    if (maxIsEven && remainderIsEven) {
      const diff = max - remainder
      if (diff <= 2) {
        return max
      }
    } else if (!maxIsEven && (!remainderIsEven || !remainder)) {
      const diff = max - remainder
      if (diff <= 2) {
        return max;
      }
    } else {
      // one is even, one is odd
    }
    max--
  }
  return max
}

function isEven(n) {
  return n % 2 === 0
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật