Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. /* fastest way to find a rectange from a specified surface*/
  2.  
  3. function findBestRectangles(area, nbRectanges) {
  4. nbRectanges = nbRectanges || 1
  5. // let area = 12008;
  6. let a = Math.sqrt(area), maxXi = Math.ceil(area / 2) + 1;
  7. // this a match to return if no match was found
  8. let x = Math.floor(a); let y = Math.ceil(a);
  9. let bismatched = { x: x, y: y, calc: x * y };
  10. let allMatched_X = []; let allMatched_Y = [];
  11. const result = {
  12. matched: null,
  13. allMatched: [],
  14. matchedBis: bismatched
  15. };
  16. // check if already good
  17. if (result.matchedBis.calc == area) {
  18. result.matched = result.matchedBis;
  19. return result;
  20. }
  21. let Xi; let Yj;
  22. Xi = x; Yj = y;
  23. console.time('findBestRectangles_' + area);
  24. if (result.matched == null)
  25. do {
  26. Yj--; // hauteur
  27. //we reset X
  28. Xi = x; // largeur
  29. do {
  30. Xi++;
  31. let calc = Yj * Xi;
  32. if (calc == area) {
  33. let bx = allMatched_X.indexOf(Xi) == -1;
  34. let bY = allMatched_Y.indexOf(Yj) == -1;
  35. if (bx && bY) {
  36. allMatched_Y.push(Xi); allMatched_X.push(Yj);
  37. let matched = { x: Xi, y: Yj };
  38. result.allMatched.push(matched);
  39. if (result.allMatched.length >= nbRectanges) {
  40. result.matched = result.allMatched.length > 0 ? result.allMatched[0] : null;
  41. console.timeEnd('findBestRectangles_' + area);
  42. return result;
  43. // break;
  44. }
  45. }
  46. }
  47. } while (Xi < maxXi)
  48. } while (Yj > 1);
  49. console.timeEnd('findBestRectangles_' + area);
  50. return result;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement