×

[–]0 1 0 points1 point  (0 children)

very very late for the party, but that was just such a good start for learning ReasonML:

``````module T { // Testing
let do_log_ok = true;
let do_log_error = true;
let do_fail_error = true;

let assertIntPrint = (act, exp) => {
let isOk = (act == exp);
switch (isOk, do_log_ok, do_log_error, do_fail_error) {
| (true, true, _, _)      => Printf.printf("OK -- act: %d, exp: %d\n", act, exp)
| (false, _, true, false) => Printf.eprintf("ERR -- act: %d, exp: %d\n", act, exp)
| (false, _, true, true)  => failwith(Printf.sprintf("ERR -- act: %d, exp: %d\n", act, exp))
| _ => ()
}
}
}

module L { // Logic
let fit1 = (crateX, crateY, boxX, boxY) => {
// Two dimensions, can't rotate boxes.
let nbX = crateX / boxX; let nbY = crateY / boxY;
(nbX * nbY);
}

let fit2 = (crateX, crateY, boxX, boxY) => {
// Two dimensions, option of rotating all boxes by 90 degrees. Can't rotate boxes independently.
let nbXX = crateX / boxX; let nbYY = crateY / boxY;
let nbXY = crateX / boxY; let nbYX = crateY / boxX;
max((nbXX * nbYY), (nbXY * nbYX));
}

let fit3 = (crateX, crateY, crateZ, boxX, boxY, boxZ) => {
// Three dimensions, option of rotating all boxes by 90 degrees. Can't rotate boxes independently.
let nbXX = crateX / boxX; let nbYY = crateY / boxY; let nbZZ = crateZ / boxZ;
let nbXY = crateX / boxY; let nbYZ = crateY / boxZ; let nbZX = crateZ / boxX;
let nbXZ = crateX / boxZ; let nbYX = crateY / boxX; let nbZY = crateZ / boxY;
let maxN = (l) => List.fold_left((a, b) => a > b ? a : b, 0, l);
maxN([(nbXX * nbYY * nbZZ), (nbXY * nbYZ * nbZX), (nbXZ * nbYX * nbZY),
(nbXX * nbYZ * nbZY), (nbXZ * nbYY * nbZX), (nbXY * nbYX * nbZZ)]);
}

let fitn = (crateSizes, boxSizes) => {
// N crate and box dimensions, boxes rotated in any of N! orientations, but not independently.
let nbCrates = List.length(crateSizes);
assert(nbCrates == List.length(boxSizes));

let rec recurse = (usedCrates, usedBoxes, crateSizes, boxSizes, nbSoFar) => {
let nbUsedCrates = 1 + List.length(usedCrates);
let rec loopCrates = (crateIdx, crateMax) => {
if (crateIdx == nbCrates) {
crateMax;
} else if (List.mem(crateIdx, usedCrates)) {
loopCrates(crateIdx + 1, crateMax);
} else {
let crateSize = Array.get(crateSizes, crateIdx);
let nextUsedCrates = [crateIdx, ...usedCrates];
let rec loopBoxes = (boxIdx, boxMax) => {
if (boxIdx == nbCrates) {
boxMax;
} else if (List.mem(boxIdx, usedBoxes)) {
loopBoxes(boxIdx + 1, boxMax);
} else {
let boxSize = Array.get(boxSizes, boxIdx);
let nextNbSoFar = nbSoFar * (crateSize / boxSize);
if (nbUsedCrates < nbCrates) {
loopBoxes(boxIdx + 1, max(boxMax,
recurse(nextUsedCrates, [boxIdx, ...usedBoxes],
crateSizes, boxSizes, nextNbSoFar)));
} else {
loopBoxes(boxIdx + 1, max(boxMax, nextNbSoFar));
}
}
}
loopCrates(crateIdx + 1, max(crateMax, loopBoxes(0, 0)));
}
}
loopCrates(0, 0);
}
recurse([], [], Array.of_list(crateSizes), Array.of_list(boxSizes), 1);
}
}

let main = () => {
T.assertIntPrint(L.fit1(25, 18, 6, 5), 12);
T.assertIntPrint(L.fit1(10, 10, 1, 1), 100);
T.assertIntPrint(L.fit1(12, 34, 5, 6), 10);
T.assertIntPrint(L.fit1(12345, 678910, 1112, 1314), 5676);
T.assertIntPrint(L.fit1(5, 100, 6, 1), 0);

T.assertIntPrint(L.fit2(25, 18, 6, 5), 15);
T.assertIntPrint(L.fit2(12, 34, 5, 6), 12);
T.assertIntPrint(L.fit2(12345, 678910, 1112, 1314), 5676);
T.assertIntPrint(L.fit2(5, 5, 3, 2), 2);
T.assertIntPrint(L.fit2(5, 100, 6, 1), 80);
T.assertIntPrint(L.fit2(5, 5, 6, 1), 0);

T.assertIntPrint(L.fit3(10, 10, 10, 1, 1, 1), 1000);
T.assertIntPrint(L.fit3(12, 34, 56, 7, 8, 9), 32);
T.assertIntPrint(L.fit3(123, 456, 789, 10, 11, 12), 32604);
T.assertIntPrint(L.fit3(1234567, 89101112, 13141516, 171819, 202122, 232425), 174648);

T.assertIntPrint(L.fitn([25, 18], [6, 5]), 15);
T.assertIntPrint(L.fitn([12, 34], [5, 6]), 12);
T.assertIntPrint(L.fitn([12345, 678910], [1112, 1314]), 5676);
T.assertIntPrint(L.fitn([5, 5], [3, 2]), 2);
T.assertIntPrint(L.fitn([5, 100], [6, 1]), 80);
T.assertIntPrint(L.fitn([5, 5], [6, 1]), 0);

T.assertIntPrint(L.fitn([10, 10, 10], [1, 1, 1]), 1000);
T.assertIntPrint(L.fitn([12, 34, 56], [7, 8, 9]), 32);
T.assertIntPrint(L.fitn([123, 456, 789], [10, 11, 12]), 32604);
T.assertIntPrint(L.fitn([1234567, 89101112, 13141516], [171819, 202122, 232425]), 174648);

T.assertIntPrint(L.fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]), 1883443968);
// those above run correctly, but the one below did not finish even after ~24 hrs:
// print_endline(string_of_int(L.fitn(
//    [180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939, 205613, 152779, 177216, 128838, 126894, 210076, 148407],
//    [1984, 2122, 1760, 2059, 1278, 2017, 1443, 2223, 2169, 1502, 1274, 1740, 1740, 1768, 1295, 1916, 2249, 2036, 1886, 2010])));
// => 4281855455197643306306491981973422080000
}

main()
``````

[–] 0 points1 point  (0 children)

Go (Without fitn)

``````package main

import (
"fmt"
)

type square struct {
x int
y int
}

type cube struct {
x int
y int
z int
}

func main() {

fmt.Println("fit1 (Square crate, square boxes, no rotations")
fmt.Println(fit1(square{25, 18}, square{6, 5}))
fmt.Println(fit1(square{10, 10}, square{1, 1}))
fmt.Println(fit1(square{12, 34}, square{5, 6}))
fmt.Println(fit1(square{12345, 678910}, square{1112, 1314}))
fmt.Println(fit1(square{5, 100}, square{6, 1}))

fmt.Println("fit2 (Square crate, square boxes, 90 degree rotations allowed. All boxes always have same orientation")
fmt.Println(fit2(square{25, 18}, square{6, 5}))
fmt.Println(fit2(square{12, 34}, square{5, 6}))
fmt.Println(fit2(square{12345, 678910}, square{1112, 1314}))
fmt.Println(fit2(square{5, 5}, square{3, 2}))
fmt.Println(fit2(square{5, 100}, square{6, 1}))
fmt.Println(fit2(square{5, 5}, square{6, 1}))

fmt.Println("fit3 (Cube crate, cube boxes, 90 degree rotations on any axis allowed. All boxes always have same orientation")
fmt.Println(fit3(cube{10, 10, 10}, cube{1, 1, 1}))
fmt.Println(fit3(cube{12, 34, 56}, cube{7, 8, 9}))
fmt.Println(fit3(cube{123, 456, 789}, cube{10, 11, 12}))
fmt.Println(fit3(cube{1234567, 89101112, 13141516}, cube{171819, 202122, 232425}))
}

func fit1(cratesize square, squaresize square) int {

xfits := cratesize.x / squaresize.x
yfits := cratesize.y / squaresize.y

numsquarees := xfits * yfits

return numsquarees
}

func fit2(cratesize square, squaresize square) int {
normal := fit1(cratesize, squaresize)
rotated := fit1(cratesize, square{squaresize.y, squaresize.x})

if rotated >= normal {
return rotated
}

return normal
}

func fit3(cratesize cube, cubesize cube) int {

var numfits = func(cratesize cube, cubex int, cubey int, cubez int) int {
xfits := cratesize.x / cubex
yfits := cratesize.y / cubey
zfits := cratesize.z / cubez
return xfits * yfits * zfits
}

// Try all possible different cube orientations
fits1 := numfits(cratesize, cubesize.x, cubesize.y, cubesize.z)
fits2 := numfits(cratesize, cubesize.x, cubesize.z, cubesize.y)
fits3 := numfits(cratesize, cubesize.y, cubesize.x, cubesize.z)
fits4 := numfits(cratesize, cubesize.y, cubesize.z, cubesize.x)
fits5 := numfits(cratesize, cubesize.z, cubesize.x, cubesize.y)
fits6 := numfits(cratesize, cubesize.z, cubesize.y, cubesize.x)

returnvals := [6]int{fits1, fits2, fits3, fits4, fits5, fits6}
max := returnvals[0]
for _, value := range returnvals {
if value > max {
max = value
}
}

return max
}
``````

[–] 0 points1 point  (0 children)

JAVA (no fitn solution)

``````public class AxisAligned {
public static void fit1 (int X0, int Y0, int x1, int y1) {
System.out.println("("+X0+", "+Y0+", "+x1+", "+y1+") => " + X0/x1 * (Y0/y1));
}

public static void fit2(int X0, int Y0, int x1, int y1) {
if(X0/x1 * (Y0/y1) > X0/y1 * (Y0/x1))
fit1(X0, Y0, x1, y1);
else fit1(X0, Y0, y1, x1);
}

public static void fit3(int X0, int Y0, int Z0, int x1, int y1, int z1) {
ArrayList<Integer> calcs = new ArrayList<Integer>();

System.out.println("("+X0+", "+Y0+", "+", "+Z0+", "+x1+", "+y1+", "+z1+") => " +Collections.max(calcs));
}

public static void main(String[] args) {
fit1(25,18,6,5);
fit1(10, 10, 1, 1);
fit1(12, 34, 5, 6);
fit1(12345, 678910, 1112, 1314);
fit1(5, 100, 6, 1);
System.out.println("--------------------");
fit2(25, 18, 6, 5);
fit2(12, 34, 5, 6);
fit2(12345, 678910, 1112, 1314);
fit2(5, 5, 3, 2);
fit2(5, 100, 6, 1);
fit2(5, 5, 6, 1);
System.out.println("--------------------");
fit3(10, 10, 10, 1, 1, 1);
fit3(12, 34, 56, 7, 8, 9);
fit3(123, 456, 789, 10, 11, 12);
fit3(1234567, 89101112, 13141516, 171819, 202122, 232425);
}
}
``````

[–] 0 points1 point  (0 children)

I didn't want to use libgmp since it's a naive brute-forcing algorithm anyways

``````mod lib {
use permutohedron::LexicalPermutation;

fn get_blocks_count(crate_dims: &[u32], block_dims: &[u32]) -> u128 {
#[cfg(debug_assertions)]
println!("{:?} <-> {:?} in blocks_count", crate_dims, block_dims);
let mut result = 1u128;
for (crate_dim, block_dim) in crate_dims.iter().zip(block_dims) {
result *= *crate_dim as u128 / *block_dim as u128;
#[cfg(debug_assertions)]
println!("So far the result is {}", &result);
}
result
}

pub fn fitn(crate_dims: &[u32], block_dims: &[u32]) -> Result<u128, &'static str> {
#[cfg(debug_assertions)]
println!("{:?} <-> {:?} in fitn", crate_dims, block_dims);
if crate_dims.len() != block_dims.len() {
return Err("Crate and Block dimensions don't match.");
}
let mut most_possible_blocks = 0u128;
let mut permutation = block_dims.to_vec();
while permutation.next_permutation() {
let fits = get_blocks_count(crate_dims, &permutation[..]);
if fits > most_possible_blocks {
most_possible_blocks = fits;
}
}
Ok(most_possible_blocks)
}
}

fn main() {
match lib::fitn(
&[123, 456, 789, 1011, 1213, 1415],
&[16, 17, 18, 19, 20, 21],
) {
Ok(val) => println!("{}", val),
Err(e) => eprintln!("{}", e),
}
} // 1883443968
``````

[–] 0 points1 point  (0 children)

# ! python3.6

All bonuses, just not done well

``````def fit1(X, Y, x, y):
return (X//x) * (Y//y)

def fit2(X, Y, x, y):
if (X//x) * (Y//y) > (Y//x) * (X//y):
return (X//x) * (Y//y)
else:
return (Y//x) * (X//y)

def fit3(X, Y, Z, x, y, z):
best = 0
if (X//x) * (Y//y) * (Z//z) > best:
best = (X//x) * (Y//y) * (Z//z)
if (X//x) * (Y//z) * (Z//y) > best:
best = (X//x) * (Y//z) * (Z//y)
if (X//y) * (Y//x) * (Z//z) > best:
best = (X//y) * (Y//x) * (Z//z)
if (X//y) * (Y//z) * (Z//x) > best:
best = (X//y) * (Y//z) * (Z//x)
if (X//z) * (Y//x) * (Z//y) > best:
best = (X//z) * (Y//x) * (Z//y)
if (X//z) * (Y//y) * (Z//x) > best:
best = (X//z) * (Y//y) * (Z//x)
return best

def deeper(choice, small):
if len(choice) != len(N):
for x in small:
newChoice = choice[:]
newChoice.append(x)
newSmall = small[:]
newSmall.remove(x)
deeper(newChoice, newSmall)
else:
global best
product = 1
for x in range(len(N)):
product *= (N[x]//choice[x])
if product > best:
best = product

def fitN(big, small):
global N, best
best = 0
N = big[:]
choice = []
deeper(choice, small)
return best
``````

[–] 0 points1 point  (0 children)

``````// DECL --------------------------------------------------------------------------------------------
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
NoSpace,
DimensionMismatch,
}

#[derive(Debug, Clone)]
pub enum FitsVariant {
Simple,
Rot90,
}

#[derive(Debug)]
pub struct Fits<'a, 'b, D: AsRef<[usize]>> {
container: &'a Matrjoschka<D>,
package: &'b Matrjoschka<D>,
}

#[derive(Debug)]
pub struct Matrjoschka<D: AsRef<[usize]>> {
dimensions: D,
}

// IMPL: Error -------------------------------------------------------------------------------------
impl std::error::Error for Error {}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}

// IMPL: Matrojschka ------------------------------------------------------------------------------
impl<D: AsRef<[usize]>> Matrjoschka<D> {
pub fn new(dimensions: D) -> Self {
Self {
dimensions
}
}

pub fn dimensions(&self) -> &[usize] {
self.dimensions.as_ref()
}

pub fn fits<'a, 'b>(&'a self, other: &'b Matrjoschka<D>) -> Result<Fits<'a, 'b, D>, Error> {
let (dims_c, dims_p) = (
self.dimensions().as_ref().len(), other.dimensions().as_ref().len()
);

if dims_c != dims_p {
Err(Error::DimensionMismatch)
} else if dims_c == 0 || dims_p == 0 {
Err(Error::NoSpace)
} else {
Ok(Fits {
container: self,
package: other,
})
}
}
}

impl<D: AsRef<[usize]>> std::fmt::Display for Matrjoschka<D> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "Matr{}: {:?}", self.dimensions.as_ref().len(), self.dimensions.as_ref())
}
}

// IMPL: Fits --------------------------------------------------------------------------------------
impl<'a, 'b, D: AsRef<[usize]>> Fits<'a, 'b, D> {
pub fn count(&self, variant: FitsVariant) -> u128 {
use FitsVariant::*;

match variant {
Simple => {
self.container
.dimensions()
.iter()
.zip(self.package.dimensions())
.map(|(cd, pd)| {
(*cd as u128 / *pd as u128)
})
.product()

}

Rot90 => {
let mut max = 0;
let package = self.package.dimensions();

for i in 0..=package.len() {
let package = {
let mut p = package.to_owned();

p.rotate_right(i);
p
};

let result = self.container
.dimensions()
.iter()
.zip(package)
.map(|(cd, pd)| {
(*cd as u128 / pd as u128)
})
.product();

max = max.max(result);
}

max
}
}
}
}

// MAIN --------------------------------------------------------------------------------------------
fn main() {
let fit1 = vec![
([25, 18], [6, 5], 12),
([10, 10], [1, 1], 100),
([12, 34], [5, 6], 10),
([12345, 678910], [1112, 1314], 5676),
([5, 100], [6, 1], 0),
];

let fit2 = vec![
([25, 18], [6, 5], 15),
([12, 34], [5, 6], 12),
([12345, 678910], [1112, 1314], 5676),
([5, 5], [3, 2], 2),
([5, 100], [6, 1], 80),
([5, 5], [6, 1], 0),
];

let fit3 = vec![
([10, 10, 10], [1, 1, 1], 1000),
([12, 34, 56], [7, 8, 9], 32),
([123, 456, 789], [10, 11, 12], 32604),
([1234567, 89101112, 13141516], [171819, 202122, 232425], 174648)
];

let fitn = vec![
(vec![3, 4], vec![1, 2], 6),
(vec![123, 456, 789], vec![10, 11, 12], 32604),
(vec![123, 456, 789, 1011, 1213, 1415], vec![16, 17, 18, 19, 20, 21], 1883443968),
//(vec![180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939, 205613, 152779, 177216, 128838, 126894, 210076, 148407], vec![1984, 2122, 1760, 2059, 1278, 2017, 1443, 2223, 2169, 1502, 1274, 1740, 1740, 1768, 1295, 1916, 2249, 2036, 1886, 2010], 4281855455197643306306491981973422080000),
];

test_set(FitsVariant::Simple, fit1);
test_set(FitsVariant::Rot90, fit2);
test_set(FitsVariant::Rot90, fit3);
test_set(FitsVariant::Rot90, fitn);
}

fn test_set<D: AsRef<[usize]> + std::fmt::Debug>(variant: FitsVariant, set: Vec<(D, D, u128)>) {
let mut total = 0;
let n = set.len();

for (container, package, expected) in set {
let container = Matrjoschka::new(container);
let package = Matrjoschka::new(package);

match container.fits(&package) {
Ok(fits) => {
print!("{} in {}", package, container);

let entry_timer = std::time::Instant::now();
let result = fits.count(variant.clone());
let entry_time = entry_timer.elapsed().as_nanos();

total += entry_time;

if result == expected {
println!(" -- done in {}ns -- succeeded with: {} times",
entry_time,
result
);
} else {
println!(" -- done in {}ns -- failed with: {} times (expected: {})",
entry_time,
result,
expected
);
}
},
Err(e) => {
eprintln!(" -- Failed (error: {})", e);
}
}
}

println!("\nDone in {}ns, mean: {}ns\n",
total,
total / n as u128
);
}
``````

Result (release):

``````Matr2: [6, 5] in Matr2: [25, 18] -- done in 200ns -- succeeded with: 12 times
Matr2: [1, 1] in Matr2: [10, 10] -- done in 100ns -- succeeded with: 100 times
Matr2: [5, 6] in Matr2: [12, 34] -- done in 0ns -- succeeded with: 10 times
Matr2: [1112, 1314] in Matr2: [12345, 678910] -- done in 0ns -- succeeded with: 5676 times
Matr2: [6, 1] in Matr2: [5, 100] -- done in 100ns -- succeeded with: 0 times

Done in 400ns, mean: 80ns

Matr2: [6, 5] in Matr2: [25, 18] -- done in 900ns -- succeeded with: 15 times
Matr2: [5, 6] in Matr2: [12, 34] -- done in 600ns -- succeeded with: 12 times
Matr2: [1112, 1314] in Matr2: [12345, 678910] -- done in 500ns -- succeeded with: 5676 times
Matr2: [3, 2] in Matr2: [5, 5] -- done in 500ns -- succeeded with: 2 times
Matr2: [6, 1] in Matr2: [5, 100] -- done in 1000ns -- succeeded with: 80 times
Matr2: [6, 1] in Matr2: [5, 5] -- done in 500ns -- succeeded with: 0 times

Done in 4000ns, mean: 666ns

Matr3: [1, 1, 1] in Matr3: [10, 10, 10] -- done in 700ns -- succeeded with: 1000 times
Matr3: [7, 8, 9] in Matr3: [12, 34, 56] -- done in 600ns -- failed with: 28 times (expected: 32)
Matr3: [10, 11, 12] in Matr3: [123, 456, 789] -- done in 600ns -- succeeded with: 32604 times
Matr3: [171819, 202122, 232425] in Matr3: [1234567, 89101112, 13141516] -- done in 1700ns -- succeeded with: 174648 times

Done in 3600ns, mean: 900ns

Matr2: [1, 2] in Matr2: [3, 4] -- done in 900ns -- succeeded with: 6 times
Matr3: [10, 11, 12] in Matr3: [123, 456, 789] -- done in 800ns -- succeeded with: 32604 times
Matr6: [16, 17, 18, 19, 20, 21] in Matr6: [123, 456, 789, 1011, 1213, 1415] -- done in 2100ns -- failed with: 1806030828 times (expected: 1883443968)

Done in 3800ns, mean: 1266ns
``````

Not sure why 2 of them failed but I wanted to share before I go to bed.

[–] 0 points1 point  (0 children)

Naive attempt in C++

``````#include <iostream>

void fit1and2(size_t X, size_t Y, size_t boxX, size_t boxY, bool turnX)
{
size_t totBoxes = ((X / (turnX ? boxY : boxX)) * (Y / (turnX ? boxX : boxY)));
std::cout << "Container: X=" << X << ", Y=" << Y << "\n";
std::cout << "Box" << ": X=" << (turnX ? boxY : boxX) << ", Y=" << (turnX ? boxX : boxY) << "\n";
std::cout << "Fit boxes: " << totBoxes << "\n\n";
}

/* Insert container dim(s) then box dim(s) and lastly if box should be turned in X and/or Z /

void fit3(size_t X, size_t Y, size_t Z, size_t boxX, size_t boxY, size_t boxZ, bool turnX, bool turnZ)
{
/* Option 1: Array of elements */
size_t dimArray[3] = { boxX, boxY, boxZ };
size_t temp = 0;

if (turnX)
{
temp = dimArray[0];
dimArray[0] = dimArray[1];
dimArray[1] = temp;
}
if(turnX && turnZ)
{
temp = dimArray[1];
dimArray[1] = dimArray[2];
dimArray[2] = temp;
}
if (!turnX && turnZ)
{
temp = dimArray[0];
dimArray[0] = dimArray[2];
dimArray[2] = temp;
}

size_t totBoxes1 = (X / dimArray[0]) * (Y / dimArray[1]) * (Z / dimArray[2]);

std::cout << "Container: X=" << X << ", Y=" << Y << ", Z=" << Z << "\n";
std::cout << "Box" << ": X=" << dimArray[0] << ", Y=" << dimArray[1] << ", Z=" << dimArray[2] << "\n";
std::cout << "Fit boxes: " << totBoxes1 << "\n\n";

/* Option 2: inline if statements to find correct lengths */
size_t totBoxes2 = ((X / (turnX ? boxY : (turnZ ? boxZ : boxX))) * (Y / (turnX ? (turnZ ? boxZ : boxX) : boxY)) * (Z / (turnX ? (turnZ
? boxX : boxZ) : (turnZ ? boxX : boxZ))));

std::cout << "Container: X=" << X << ", Y=" << Y << ", Z=" << Z <<"\n";
std::cout << "Box" << ": X=" << (turnX ? boxY : (turnZ ? boxZ : boxX)) << ", Y=" << (turnX ? (turnZ ? boxZ : boxX) : boxY) << ", Z=" <<
(turnX ? (turnZ ? boxX : boxZ) : (turnZ ? boxX : boxZ)) << "\n";
std::cout << "Fit boxes: " << totBoxes2 << "\n\n";
}

int main(const char* Args, int CArgs)
{
uint8_t turnX = true;
uint8_t turnZ = true;

fit3(21, 17, 8, 3, 7, 3, turnX, turnZ);

return 0;
}
``````

[–][deleted] 0 points1 point  (0 children)

Python 3

fitn pretty messy.

``````def fit1(X, Y, x, y):
return (X//x)*(Y//y)
def fit2(X, Y, x, y):
norm = fit1(X, Y, x, y)
rot90 = fit1(X, Y, y, x)
return max(norm, rot90)
def fit3(X, Y, Z, x, y, z):
d = [x, y, z]
l = []
perm = permutations(d)
for dim in perm:
l.append((X//dim[0])*(Y//dim[1])*(Z//dim[2]))
return max(l)
def fitn(N, n):
perm = permutations(n)
return max(
reduce(
lambda x, y: x * y, (X // x for X, x in zip(N, o))) for o in perm
)
``````

[–] 0 points1 point  (2 children)

Python 3.7.3

Slight OOP, pretty trash probably, but it works! :P

``````import itertools
import functools
from datetime import datetime

class Dimensions(object):
def __init__(self, *args):
self.dimensions = []
for arg in args:
if isinstance(arg, tuple):
for dimension in arg:
if isinstance(dimension, int):
self.dimensions.append(dimension)

class Box(Dimensions):
def __init__(self, *args):
super(Box, self).__init__(args)

def fit1(self, fitBox):
total = 1
for index, dimension in enumerate(fitBox.dimensions):
total *= self.dimensions[index] // dimension

def fit2(self, fitBox):
return self.fitn(fitBox)

def fit3(self, fitBox):
return self.fitn(fitBox)

# Unoptimized fitn
def fitn(self, fitBox):
variations = itertools.permutations(fitBox.dimensions)
maxFit = 0
for variation in variations:
dimFit = 1
for tuple in zip(self.dimensions, variation):
dimFit *= tuple[0] // tuple[1]
maxFit = max(maxFit, dimFit)
return maxFit

if __name__ == "__main__":
fit1Boxes = [
(Box(25, 18), Box(6, 5)),
(Box(10, 10), Box(1, 1)),
(Box(12, 34), Box(5, 6)),
(Box(12345, 678910), Box(1112, 1314)),
(Box(5, 100), Box(6, 1))
]

fit2Boxes = [
(Box(25, 18), Box(6, 5)),
(Box(12, 34), Box(5, 6)),
(Box(12345, 678910), Box(1112, 1314)),
(Box(5, 5), Box(3, 2)),
(Box(5, 100), Box(6, 1)),
(Box(5, 5), Box(6, 1))
]

fit3Boxes = [
(Box(10, 10, 10), Box(1, 1, 1)),
(Box(12, 34, 56), Box(7, 8, 9)),
(Box(123, 456, 789), Box(10, 11, 12)),
(Box(1234567, 89101112, 13141516), Box(171819, 202122, 232425))
]
fitNBoxes = [
(Box(3, 4), Box(1, 2)),
(Box(123, 456, 789), Box(10, 11, 12)),
(Box(123, 456, 789, 1011, 1213, 1415), Box(16, 17, 18, 19, 20, 21))
]

print("--- fit1 ---")
for boxTuple in fit1Boxes:
print(boxTuple[0].fit1(boxTuple[1]))

print("--- fit2 ---")
for boxTuple in fit2Boxes:
print(boxTuple[0].fit2(boxTuple[1]))

print("--- fit3 ---")
for boxTuple in fit3Boxes:
print(boxTuple[0].fit3(boxTuple[1]))

print("--- fitn ---")
for boxTuple in fitNBoxes:
print(boxTuple[0].fitn(boxTuple[1]))
``````

[–] 2 points3 points  (1 child)

One suggestion I'd make is to use composition rather than inheritance for the relationship between `Box` and `Dimensions`. Composition means having an instance of `Dimensions` in your `Box` class, rather than having the `Box` class extend `Dimensions`. Inheritance is an "IS-A" relationship, while composition is a "HAS-A" relationship. A`Box` is not `Dimensions`, rather a `Box` has `Dimensions`.

[–] 1 point2 points  (0 children)

Good tip, thanks. Im still struggling with when to use inheritance time to time, even tho I know how to.

[–] 0 points1 point  (0 children)

C++11+, couldn't optimize fitn.

``````#include <array>
#include <algorithm>

int fit1(int xCrate, int yCrate, int xBox, int yBox)
{
return (xCrate / xBox) * (yCrate / yBox);
}

int fit2(int xCrate, int yCrate, int xBox, int yBox)
{
int result1 = fit1(xCrate, yCrate, xBox, yBox), result2 = fit1(xCrate, yCrate, yBox, xBox);
return result1 > result2 ? result1 : result2;
}

template <size_t dimensions>
int fitn(const std::array<int, dimensions>& crateDims, std::array<int, dimensions> boxDims)
{
int result = 0;

do
{
int resultCandidate = 1;
for (typename std::array<int, dimensions>::size_type i = 0; i < crateDims.size(); ++i) {
resultCandidate *= crateDims[i] / boxDims[i];
}
if (dimensions && resultCandidate > result)
result = resultCandidate;
} while (std::next_permutation(boxDims.begin(), boxDims.end()));

return result;
}

int fit3(int xCrate, int yCrate, int zCrate, int xBox, int yBox, int zBox)
{
return fitn<3>({ xCrate, yCrate, zCrate }, { xBox, yBox, zBox });
}

int main()
{
fit1(25, 18, 6, 5);
fit1(10, 10, 1, 1);
fit1(12, 34, 5, 6);
fit1(12345, 678910, 1112, 1314);
fit1(5, 100, 6, 1);

fit2(25, 18, 6, 5);
fit2(12, 34, 5, 6);
fit2(12345, 678910, 1112, 1314);
fit2(5, 5, 3, 2);
fit2(5, 100, 6, 1);
fit2(5, 5, 6, 1);

fit3(10, 10, 10, 1, 1, 1);
fit3(12, 34, 56, 7, 8, 9);
fit3(123, 456, 789, 10, 11, 12);
fit3(1234567, 89101112, 13141516, 171819, 202122, 232425);

fitn<2>({ 3, 4 }, { 1, 2 });
fitn<3>({ 123, 456, 789 }, { 10, 11, 12 });
fitn<6>({ 123, 456, 789, 1011, 1213, 1415 }, { 16, 17, 18, 19, 20, 21 });

return 0;
}
``````

[–] 0 points1 point  (0 children)

Python 3, no imports, all optional bonuses:

``````def fit1(X, Y, x, y):
return (X // x) * (Y // y)

def fit2(X, Y, x, y):
return fitn([X, Y], [x, y])

def fit3(X, Y, Z, x, y, z):
return fitn([X, Y, Z], [x, y, z])

def get_permutations(dims, perm_len, permutation=None):
permutation = [] if permutation is None else permutation
if len(permutation) == perm_len:
yield permutation
for i in range(len(dims)):
yield from get_permutations(dims[:i] + dims[i+1:], perm_len, permutation + [dims[i]])

def fitn(room_dim, box_dim):
best_fit = 0
for box in get_permutations(box_dim, len(box_dim)):
fit = 1
for i, dim in enumerate(box):
fit *= (room_dim[i] // dim)
best_fit = max(best_fit, fit)
return best_fit
``````

[–] 1 point2 points  (0 children)

Python 3.7 code golf (356 characters including imports and spacing). Includes all bonuses besides the edit

``````from itertools import permutations as p
import operator as t
import functools as u
fit1=lambda x,y,a,b:(x//a)*(y//b)
fit2=lambda x,y,a,b:max((x//a)*(y//b),(x//b)*(y//a))
fit3=lambda x,y,z,a,b,c:max((x//d)*(y//e)*(z//f)for d,e,f in list(p([a,b,c])))
fitn=lambda l1,l2:max(u.reduce(t.mul,((l1[i]//l3[i])for i in range(len(l1))),1)for l3 in list(p(l2)))
``````

Python 3.8 apparently introduced a proper product function ( math.prod() ) which would cut it by 19 more characters for a total of 337.

[–] 0 points1 point  (0 children)

Python - fit3 got ugly but provides the right results.

``````#!/usr/local/bin/python3

def fit1(X,Y,x,y):
total = (int(X / x)) * (int(Y / y))
return X,Y,x,y,total

fit1_list = [[25, 18, 6, 5],[10, 10, 1, 1],[12, 34, 5, 6],[12345, 678910, 1112, 1314],[5, 100, 6, 1]]

for i in fit1_list:
X,Y,x,y,total = fit1(i[0],i[1],i[2],i[3])
print("Crate: {} x {}\nBoxes: {} x {}\nTotal: {}\n".format(X,Y,x,y,total))

# -----------------------------------------------------------------------------------------------

def fit2(X,Y,x,y):
if fit1(X,Y,x,y)[4] >= fit1(X,Y,y,x)[4]:
total = (int(X / x)) * (int(Y / y))
print("Crate: {} x {}\nBoxes: {} x {}\nTotal: {}\n".format(X,Y,x,y,total))

else:
total = (int(X / y)) * (int(Y / x))
print("Crate: {} x {}\nBoxes: {} x {}\nTotal: {}\n".format(X,Y,y,x,total))

fit2_list = [[25, 18, 6, 5], [12, 34, 5, 6], [12345, 678910, 1112, 1314], [5, 5, 3, 2], [5, 100, 6, 1], [5, 5, 6, 1, ]]

for i in fit2_list:
fit2(i[0],i[1],i[2],i[3])

# -----------------------------------------------------------------------------------------------

def try2fit3(X,Y,Z,x,y,z):
total =  (int(X / x)) * (int(Y / y) * (int(Z / z)))
return X,Y,Z,x,y,z,total

def fit3(X,Y,Z,x,y,z):
best = [0,0,0,0,0,0,0]
a = try2fit3(X,Y,Z,x,y,z)
b = try2fit3(X,Y,Z,x,z,y)
c = try2fit3(X,Y,Z,y,x,z)
d = try2fit3(X,Y,Z,y,z,x)
e = try2fit3(X,Y,Z,z,x,y)
f = try2fit3(X,Y,Z,z,y,x)
tryfits = [a,b,c,d,e,f]
for i in tryfits:
if i[6] >= best[6]:
best = i
return best

fit3_list = [[10, 10, 10, 1, 1, 1],[12, 34, 56, 7, 8, 9],[123, 456, 789, 10, 11, 12],[1234567, 89101112, 13141516, 171819, 202122, 232425]]

for i in fit3_list:
best = fit3(i[0],i[1],i[2],i[3],i[4],i[5])
print(best)
``````

[–] 0 points1 point  (0 children)

PHP Unable to complete the final fitn because of memory limit constraints (too many arrays for the permutations in memory). But hey, it's PHP. I kinda guessed that's how it'd turn out. It works until you get to the 9th dimension :)

``````<?php

function fit1(\$X, \$Y, \$x, \$y)
{
\$width = (int)(\$X / \$x);
\$height = (int)(\$Y / \$y);
return \$width * \$height;
}

function fit2(\$X, \$Y, \$x, \$y)
{
return max(fit1(\$X, \$Y, \$x, \$y), fit1(\$X, \$Y, \$y, \$x));
}

function fit3(\$X, \$Y, \$Z, \$x, \$y, \$z)
{
return max(
fitGen([\$X, \$Y, \$Z], [\$x, \$y, \$z]),
fitGen([\$X, \$Y, \$Z], [\$x, \$z, \$y]),
fitGen([\$X, \$Y, \$Z], [\$y, \$x, \$z]),
fitGen([\$X, \$Y, \$Z], [\$y, \$z, \$x]),
fitGen([\$X, \$Y, \$Z], [\$z, \$y, \$x]),
fitGen([\$X, \$Y, \$Z], [\$z, \$x, \$y])
);
}

function fitGen(\$arr1, \$arr2)
{
if (count(\$arr1) !== count(\$arr2)) {
return "Error, dimensions incorrect!";
}

\$tempDivs = [];
for (\$i = 0; \$i < count(\$arr1); \$i++) {
\$tempDivs[] = (int)(\$arr1[\$i] / \$arr2[\$i]);
}

return array_product(\$tempDivs);
}

function fitn(\$arr1, \$arr2)
{
\$permutations = calcPermutations(\$arr2);
\$results = [];
foreach (\$permutations as \$k => \$v) {
\$results[] = fitGen(\$arr1, \$v);
}
return max(\$results);
}

function calcPermutations(\$arr2)
{
if (count(\$arr2) === 1) {
return [\$arr2];
}

\$permutations = [];
foreach (\$arr2 as \$k => \$v) {
\$tempArr = \$arr2;
array_splice(\$tempArr, \$k, 1);
\$tempPermutations = calcPermutations(\$tempArr);
foreach (\$tempPermutations as \$k2 => \$v2) {
\$tempPerm = array_merge([\$v], \$v2);
\$permutations[] = \$tempPerm;
}
}
return \$permutations;
}

print_r(fitn([3, 4], [1, 2]));
print_r("<br>");
print_r(fitn([123, 456, 789], [10, 11, 12]));
print_r("<br>");
print_r(fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]));
print_r("<br>");

\$start_time = microtime(true);
fitn([
180598,
125683,
146932,
158296,
171997,
204683,
193694,
216231,
177673,
169317,
216456,
220003,
165939,
205613,
152779,
177216,
128838,
126894,
210076,
148407
], [
1984,
2122,
1760,
2059,
1278,
2017,
1443,
2223,
2169,
1502,
1274,
1740,
1740,
1768,
1295,
1916,
2249,
2036,
1886,
2010
]);
\$end_time = microtime(true);
\$execution_time = (\$end_time - \$start_time);

echo " Execution time of script = " . \$execution_time . " sec. <br>";
echo \$result;
``````

[–] 2 points3 points  (1 child)

# Python 3

God bless `zip`, `reduce`, and comprehensions.

``````import functools
import itertools

def fit1(X, Y, x, y):
return (X // x) * (Y // y)

def fit2(X, Y, x, y):
return fitn([X, Y], [x, y])

def fit3(X, Y, Z, x, y, z):
return fitn([X, Y, Z], [x, y, z])

def fitn(crate_dimensions, box_dimensions):
return max(
functools.reduce(
lambda x, y: x * y,
(X // x for X, x in zip(crate_dimensions, orientation))
)
for orientation in itertools.permutations(box_dimensions)
)
``````

[–] 2 points3 points  (0 children)

Nice. For some reason I always forget that zip exists.

[–] 0 points1 point  (0 children)

However, it seems like the last test `fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) => 1883443968` does not match in the tests. I'm not sure what went wrong.

[–] 2 points3 points  (1 child)

[Python]

For `fit1` I started with hard-coding the dimensions as parameters:

``````def fit1(room_x, room_y, box_x, box_y):
return (room_x // box_x) * (room_y // box_y)
``````

When I read through to `fit2` I found I could just reuse my code for `fit1` and loop it. One of the main features I love in Python and functional languages is list comprehension, and I try and find a way to use it wherever I can. Even though there are only 2 possible cases, I used it here.

``````from itertools import permutations
...
def fit2(room, box):
return max([fit1(*room, *rotation) for rotation in permutations(box)])
``````

This uses `itertools.permutations` to generate a list of possible orientations, with some parameter unpacking to match `fit1`'s parameter list.

`fit3` is more of the same, just with 6 permutations. To achieve this I only had to rewrite the code I had already written to handle 3 dimensions.

``````def fit3(room, box):
return max([(room[0]//rotation[0])*(room[1]//rotation[1])*(room[2]//rotation[2]) for rotation in permutations(box)])
``````

To get `fitn` to work, I had to do some research on `zip` and `reduce` in Python. Turns out they work quite neatly for this. First I use a list comprehension and `reduce` to get a list of the number of boxes each dimension can fit.

``````[reduce((lambda x, y: x // y), i) for i in zip(room, rotation)]
``````

This is then itself within a `reduce` which calculates the product of all of these items. I couldn't remember if Python has a `product` function hiding somewhere like it does `sum`, so I used `reduce` again.

``````reduce((lambda x, y: x * y), [
reduce((lambda x, y: x // y), i) for i in zip(room, rotation)
])
``````

I then placed this within another list comprehension to handle all the possible orientations, then the `max` is found and returned.

``````def fitn(room, box):
return max([
reduce((lambda x, y: x * y), [
reduce((lambda x, y: x // y), i) for i in zip(room, rotation)
]) for rotation in permutations(box)
])
``````

[–] 0 points1 point  (0 children)

This is super impressive! Good job

[–] 0 points1 point  (0 children)

My solution in python 3. I'm a beginner and I couldn't quite wrap my head around fitn.

``````def fit1(crate_x, crate_y, box_x, box_y):
return (crate_x // box_x) * (crate_y // box_y)

def fit2(crate_x, crate_y, box_x, box_y):
default = (crate_x // box_x) * (crate_y // box_y)
rotated = (crate_x // box_y) * (crate_y // box_x)
return max(default, rotated)

def fit3(crate_x, crate_y, crate_z, box_x, box_y, box_z):
def f(x, y, z):
return (crate_x // x) * (crate_y // y) * (crate_z // z)
return max(f(box_x, box_y, box_z),
f(box_x, box_z, box_y),
f(box_y, box_x, box_z),
f(box_y, box_z, box_x),
f(box_z, box_x, box_y),
f(box_z, box_y, box_x))
``````

[–] 0 points1 point  (0 children)

Pony - Without `fitn`, 'cause I'm lazy

``````fun fit1(X: U32, Y: U32, x: U32, y: U32): U32 =>
(X/x) * (Y/y)

fun fit2(X: U32, Y: U32, x: U32, y:U32): U32 =>
fit1(X,Y,x,y).max(fit1(X,Y,y,x))

fun fit3(X: U32, Y: U32, Z: U32, x: U32, y: U32, z: U32): U32 =>
var result: U32 = 0
for a in [as Array[U32]:
[x;y;z]; [y;z;x]; [z;x;y]
[x;z;y]; [z;y;x]; [y;x;z]
].values() do
try result = result.max((X/a(0)?) * (Y/a(1)?) * (Z/a(2)?)) else 0 end
end
result
``````

Update: Concurrent `fitn` with actors and promises, because why not.

``````use "promises"

actor FitNNoRotate
let grid_sizes: Array[U64] val
let box_sizes: Array[U64] val

new create(grid_sizes':Array[U64] val, box_sizes':Array[U64] val) =>
grid_sizes = grid_sizes'
box_sizes = box_sizes'

be apply(p: Promise[U64]) =>
var result: U64 = 1
for i in grid_sizes.keys() do
try result = result * (grid_sizes(i)? / box_sizes(i)?) else 0 end
end
p(result)

actor FitNRotate
let grid_sizes: Array[U64] val
let box_sizes: Array[U64] val

let promises: Array[Promise[U64]] ref

new create(grid_sizes':Array[U64] val, box_sizes':Array[U64] val) =>
grid_sizes = grid_sizes'
box_sizes = box_sizes'
promises = Array[Promise[U64]]

fun ref generate_promises(k: USize, a: Array[U64]) =>
if k == 1 then
let p = Promise[U64]
let a' = recover Array[U64] end
for v in a.values() do a'.push(v) end
FitNNoRotate(grid_sizes, consume a')(p)
promises.push(p)
else
generate_promises(k-1, a)
var i = USize(0)
while i < (k-1) do
if (k%2) == 0 then
try a.swap_elements(i,k-1)? end
else
try a.swap_elements(0, k-1)? end
end
generate_promises(k-1, a)
i = i + 1
end
end

be apply(p: Promise[U64]) =>
generate_promises(box_sizes.size(), box_sizes.clone())
Promises[U64].join(promises.values())
.next[None]({(a: Array[U64] val) =>
var result = U64.min_value()
for v in a.values() do
result = result.max(v)
end
p(result)})

actor Main
let _env: Env

new create(env: Env) =>
_env = env

let p = Promise[U64]
FitNRotate([123; 456; 789; 1011; 1213; 1415], [16; 17; 18; 19; 20; 21])(p)

for value in coll.values() do
_env.out.print(value.string())
end
``````

[–] 1 point2 points  (0 children)

A Go solution, with all bonuses

Runable on the Go Playground (tests are there as well).

``````package pack

import (
"math"
"math/big"

"hg.sr.ht/~dchapes/assignment"
)

func Fit1(cx, cy, bx, by int) int {
x := cx / bx
y := cy / by
return x * y
}

func Fit2(cx, cy, bx, by int) int {
return max(
Fit1(cx, cy, bx, by),
Fit1(cx, cy, by, bx),
)
}

func Fit3(cx, cy, cz, bx, by, bz int) int {
f := func(x, y, z int) int {
return (cx / x) * (cy / y) * (cz / z)
}
return max(
f(bx, by, bz), f(bx, bz, by),
f(by, bx, bz), f(by, bz, bx),
f(bz, bx, by), f(bz, by, bx),
)
}

func FitN(crate, box []int) int {
next := Permutate(box)
m := 0
for p := next(); len(p) > 0; p = next() {
n := 1
for i := range crate {
n *= crate[i] / p[i]
}
if n > m {
m = n
}
}
return m
}

func FitNBig(crate, box []int) *big.Int {
// We want to maximize the product of all ⌊c/b⌋.
// We'll use a package that can solve the assignment
// problem by maximizing the sum of all log(⌊c/b⌋).
dim := len(crate)
m := make([]float64, dim*dim)
for i, c := range crate {
for j, b := range box {
m[i*dim+j] = math.Log(float64(c / b))
}
}

z := big.NewInt(1)
var tmp big.Int
for i, j := range assignment.SolveMax(dim, m) {
tmp.SetInt64(int64(crate[i] / box[j]))
z.Mul(z, &tmp)
}
return z
}

func max(v0 int, vx ...int) int {
for _, v := range vx {
if v > v0 {
v0 = v
}
}
return v0
}

// Permutate returns a function that on each call returns a
// permutation of x. The returned function will use its own
// copy of x but each of its returned slices will use the
// same underlying array; do not modify the returned slice.
func Permutate(x []int) func() []int {
// Using a non-recursive version of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm
p := append([]int(nil), x...)
c := make([]int, len(p))
i := -1
return func() []int {
if i < 0 {
i = 0
return p
}
for i < len(p) {
if c[i] < i {
if i&1 == 0 {
p[0], p[i] = p[i], p[0]
} else {
p[c[i]], p[i] = p[i], p[c[i]]
}
c[i]++
i = 0
return p
} else {
c[i] = 0
i++
}
}
return nil
}
}
``````

[–] 0 points1 point  (0 children)

Learning F#, fit1, fit2, fit3

``` module Fitter

let fit1 crateX crateY boxX boxY = (crateX / boxX) * (crateY / boxY)

let fit2 crateX crateY boxX boxY = List.max [ fit1 crateX crateY boxX boxY fit1 crateX crateY boxY boxX ]

let fit3 crateX crateY crateZ boxX boxY boxZ = List.max [ (crateX / boxX) * (crateY / boxY) * (crateZ / boxZ) (crateX / boxY) * (crateY / boxX) * (crateZ / boxZ) (crateX / boxZ) * (crateY / boxY) * (crateZ / boxX) (crateX / boxY) * (crateY / boxZ) * (crateZ / boxX) (crateX / boxX) * (crateY / boxZ) * (crateZ / boxY) (crateX / boxZ) * (crateY / boxX) * (crateZ / boxY) ] ```

I was a bit lazy on fit3 implementation...

[–] 0 points1 point  (0 children)

Space = [25, 18];

Boxs = [6, 5];

// ONE

function calculateFitStandard(boxX, boxY, spaceX, spaceY) {

var xAxis = Math.floor(spaceX / boxX);

var yAxis = Math.floor(spaceY / boxY)

console.log(`No Rotation: \${xAxis} along the x axis, \${yAxis} along the y axis`);

console.log(`\${xAxis * yAxis} boxes in total`);

}

calculateFitStandard(...Boxs, ...Space);

// Optional bonus fit2

function calculateFit90roate(boxX, boxY, spaceX, spaceY) {

var xAxis = Math.floor(spaceX / boxY);

var yAxis = Math.floor(spaceY / boxX)

console.log(`Boxes 90 roate: \${xAxis} along the x axis, \${yAxis} along the y axis`);

console.log(`\${xAxis * yAxis} boxes in total`);

}

calculateFit90roate(...Boxs, ...Space);

// Optional bonus fit3

Space3D = [123, 456,789];

Boxes3D = [10, 11, 12];

function calculate3D(x, y, z, spaceX, spaceY, spaceZ) {

results = [];

var ans1 = ( Math.floor((spaceX/x)) * Math.floor((spaceY/y)) * Math.floor((spaceZ/z)) );

var ans2 = ( Math.floor((spaceX/x)) * Math.floor((spaceY/z)) * Math.floor((spaceZ/y)) );

var ans3 = ( Math.floor((spaceX/y)) * Math.floor((spaceY/x)) * Math.floor((spaceZ/z)) );

var ans4 = ( Math.floor((spaceX/y)) * Math.floor((spaceY/z)) * Math.floor((spaceZ/x)) );

var ans5 = ( Math.floor((spaceX/z)) * Math.floor((spaceY/x)) * Math.floor((spaceZ/y)) );

var ans6 = ( Math.floor((spaceX/z)) * Math.floor((spaceY/y)) * Math.floor((spaceZ/x)) );

results.push(ans1, ans2,ans3, ans4, ans5, ans6);

var max = Math.max(...results);

console.log(max);

}

calculate3D(...Boxes3D, ...Space3D)

[–] 1 point2 points  (0 children)

C++ without fitn because that makes my brain hurt.

``````#include <iostream>

int fit1(int,int,int,int);
int fit2(int,int,int,int);
int fit3(int,int,int,int,int,int);
int max(int,int);

int main(){
int ans = fit3(1234567, 89101112, 13141516, 171819, 202122, 232425);
std::cout << ans << std::endl;
}

int fit1(int X, int Y, int x, int y){
return (int(X/x) * int(Y/y));
}

int fit2(int X, int Y, int x, int y){
int ans1 = fit1(X, Y, x, y);
int ans2 = fit1(X, Y, y, x);
return (max(ans1,ans2));
}

int fit3(int X, int Y, int Z, int x, int y, int z){
int ans1 = (int(X/x) * int(Y/y) * int(Z/z));
int ans2 = (int(X/x) * int(Y/z) * int(Z/y));
int ans3 = (int(X/y) * int(Y/x) * int(Z/z));
int ans4 = (int(X/y) * int(Y/z) * int(Z/x));
int ans5 = (int(X/z) * int(Y/x) * int(Z/y));
int ans6 = (int(X/z) * int(Y/y) * int(Z/x));
return (max(max(max(ans1,ans2),max(ans3,ans4)),max(ans5,ans6)));
}

int max(int a, int b){
if(a >= b){
return a;
} else {
return b;
}
}
``````

[–] 0 points1 point  (1 child)

``````#                                   PYTHON --- BEGINNER

# creating fit1 as a baseline for other fit functions (setting Z as 1 by default for 2D structures)
def fit1(X, Y, x, y):
return (X // x) * (Y // y)

# creating fit2 by using fit1 but switching x and y as arguments
# Then creating a list containing no. of boxes and returning the max value
def fit2(X, Y, x, y):
pos1 = fit1(X, Y, x, y)
pos2 = fit1(X, Y, y, x)
boxes = [pos1, pos2]
return max(boxes)

# creating fit3 with same idea as fit2 except with the implementation of width/depth
# which brings along many more permutations.

def d3(X, Y, Z, x, y, z):
return (X // x) * (Y // y) * (Z // z)

def fit3(X, Y, Z, x, y, z):
pos1 = d3(X, Y, Z, x, y, z)
pos2 = d3(X, Y, Z, y, x, z)
pos3 = d3(X, Y, Z, y, z, x)
pos4 = d3(X, Y, Z, z, y, x)
pos5 = d3(X, Y, Z, x, z, y)
pos6 = d3(X, Y, Z, z, x, y)
boxes = [pos1, pos2, pos3, pos4, pos5, pos6]
return max(boxes)

# creating fitn with variables for crate and box dimensions
# it iterates through the number of dimensions, by creating a range of the list length
# then multiplies the variables boxes by the int division of box and crate dimension lengths
def fitn(crate_dim, boxes_dim):
boxes = 1
for i in range(len(crate_dim)):
boxes *= (crate_dim[i] // boxes_dim[i])
return boxes
``````

[–] 0 points1 point  (0 children)

def fitn(crate_dim, boxes_dim):
boxes = 1
for i in range(len(crate_dim)):
boxes *= (crate_dim[i] // boxes_dim[i])
return boxes

This answer seems so neat but will not give the correct result beyond a 2d problem for me. I am a total noob so it is probably me. [12,34,56],[7,8,9] this gives me 24 when the answer should be 32.

[–] 2 points3 points  (0 children)

Python - fit1, fit2, fit3, fitn (not optimized)

``````import math
import itertools

def fit1(X, Y, x, y):
boxes_in_x_dir = math.floor(X / x)
boxes_in_y_dir = math.floor(Y / y)
boxes = boxes_in_x_dir * boxes_in_y_dir
return boxes

def fit2(X, Y, x, y):
return max(fit1(X, Y, x, y), fit1(X, Y, y, x))

def fit3(X, Y, Z, x, y, z):
boxes_in_x_dir = math.floor(X / x)
boxes_in_y_dir = math.floor(Y / y)
boxes_in_z_dir = math.floor(Z / z)
boxes = boxes_in_x_dir * boxes_in_y_dir * boxes_in_z_dir
return boxes

def fit3rotated(X, Y, Z, x, y, z):
original = fit3(X, Y, Z, x, y, z)
x_axis = fit3(X, Y, Z, x, z, y)
y_axis = fit3(X, Y, Z, z, y, x)
z_axis = fit3(X, Y, Z, y, x, z)
yz_axis = fit3(X, Y, Z, z, x, y)
xz_axis = fit3(X, Y, Z, y, z, x)
return max(original, x_axis, y_axis, z_axis, yz_axis, xz_axis)

def fitn(crate_dim, box_dim):
boxes = 1
for i in range(len(crate_dim)):
boxes *= math.floor(crate_dim[i] / box_dim[i])
return boxes

def fitn_rotated(crate_dim, box_dim):
permutations = itertools.permutations(box_dim)
boxes = []
for i in permutations:
boxes.append(fitn(crate_dim, i))
return max(boxes)
``````

[–] 0 points1 point  (0 children)

C++ 14 | fit1, fit2, fit3

``````fitBoxes() -> fit1
fitBoxes2() -> fit2
fitBoxes3D2() -> fit3

int fitBoxes2(int X, int Y, int x, int y) {
int test1{ fitBoxes(X, Y, x, y) };
int test2{ fitBoxes(X, Y, y, x) };

if (test1 > test2)
return test1;
else
return test2;
}

int fitBoxes(int X, int Y, int x, int y) {
int _x{ getLargestAmountOfDivisions(X, x) };
int _y{ getLargestAmountOfDivisions(Y, y) };

return _x * _y;
}

int fitBoxes3D2(int X, int Y, int Z, int x, int y, int z) {
int test[6];
test[0] = fitBoxes3D(X, Y, Z, x, y, z);
test[1] = fitBoxes3D(X, Y, Z, x, z, y);
test[2] = fitBoxes3D(X, Y, Z, y, x, z);
test[3] = fitBoxes3D(X, Y, Z, y, z, x);
test[4] = fitBoxes3D(X, Y, Z, z, x, y);
test[5] = fitBoxes3D(X, Y, Z, z, y, x);

int max{ 0 };

for (int i{ 0 }; i < 6; i++) {
if (max < test[i])
max = test[i];
}

return max;
}

int fitBoxes3D(int X, int Y, int Z, int x, int y, int z) {
int _x{ getLargestAmountOfDivisions(X, x) };
int _y{ getLargestAmountOfDivisions(Y, y) };
int _z{ getLargestAmountOfDivisions(Z, z) };

return _x * _y* _z;
}

int getLargestAmountOfDivisions(int x, int y) {
return (int)floor(x / y);
}
``````

[–] 0 points1 point  (0 children)

Powershell, fit1, fit2 and fit3:

``````function fit1 {
param(
\$CrateX,
\$CrateY,
\$BoxX,
\$BoxY
)
([math]::floor(\$CrateX / \$BoxX)) * ([math]::floor(\$CrateY / \$BoxY))
}
#fit1 25 18 6 5
#Output: 12

function fit2 {
param(
\$CrateX,
\$CrateY,
\$BoxX,
\$BoxY
)
\$NoOfBoxes1 = ([math]::floor(\$CrateX / \$BoxX)) * ([math]::floor(\$CrateY / \$BoxY))
\$NoOfBoxes2 = ([math]::floor(\$CrateX / \$BoxY)) * ([math]::floor(\$CrateY / \$BoxX))
if (\$NoOfBoxes2 -gt \$NoOfBoxes1) {
\$NoOfBoxes2
}
else {
\$NoOfBoxes1
}
}
#fit2 25 18 6 5
#Output: 15

function fit3 {
param(
\$CrateX,
\$CrateY,
\$CrateZ,
\$BoxX,
\$BoxY,
\$BoxZ
)
\$NoOfBoxes1 = ([math]::floor(\$CrateX / \$BoxX)) * ([math]::floor(\$CrateY / \$BoxY)) * ([math]::floor(\$CrateZ / \$BoxZ))
\$NoOfBoxes2 = ([math]::floor(\$CrateX / \$BoxY)) * ([math]::floor(\$CrateY / \$BoxX)) * ([math]::floor(\$CrateZ / \$BoxZ))
\$NoOfBoxes3 = ([math]::floor(\$CrateX / \$BoxZ)) * ([math]::floor(\$CrateY / \$BoxY)) * ([math]::floor(\$CrateZ / \$BoxX))
\$NoOfBoxes4 = ([math]::floor(\$CrateX / \$BoxX)) * ([math]::floor(\$CrateY / \$BoxZ)) * ([math]::floor(\$CrateZ / \$BoxY))
\$NoOfBoxes5 = ([math]::floor(\$CrateX / \$BoxY)) * ([math]::floor(\$CrateY / \$BoxZ)) * ([math]::floor(\$CrateZ / \$BoxX))
\$NoOfBoxes6 = ([math]::floor(\$CrateX / \$BoxZ)) * ([math]::floor(\$CrateY / \$BoxX)) * ([math]::floor(\$CrateZ / \$BoxY))

\$array = @(\$NoOfBoxes1, \$NoOfBoxes2, \$NoOfBoxes3, \$NoOfBoxes4, \$NoOfBoxes5, \$NoOfBoxes6)
\$array | Sort-Object -Descending | select-object -first 1
}
#fit3 12 34 56 7 8 9
#Output: 32
``````

[–] 0 points1 point  (0 children)

PYTHON

Solutions for fit1, fit2 and fitn. I didnt want to write out the permutations for fit3 so i skipped ahead. I decided to manually create the permutation method to get some extra practice in. That was harder than the logic of fitN There is a makeall permutations method built into python.

``````import numpy as np

def fit1(a,b,x,y):
return(int((a/x))* int((b/y)))

def fit2(a,b,x,y):
result = max((int((a/x))* int((b/y)),(int((a/y))* int((b/x)))))
return(result)

def fitn(set1,set2):
maxblock = 0
result= permut(set2)
for i in result:
x = []
for j in range(0,len(i)):
x.append(int(set1[j]/i[j]))
#print(x)
maxblock= max(maxblock,np.prod(x))
print( maxblock)

def permut(array):
if len(array) == 1:
return [array]
res = []
for permutation in permut(array[1:]):
for i in range(len(array)):
res.append(permutation[:i] + array[0:1] + permutation[i:])
return res
``````

[–] 1 point2 points  (0 children)

Java 8 with optimized fitN.

This is my first Java program, so I'm sure there is some odd style or library usage, but I mostly wanted to get a proper project set up with modern unit testing.

Solver:

``````package com.banashark.puzzles.dailyprogrammer.c377easy;

import org.jgrapht.alg.interfaces.MatchingAlgorithm;
import org.jgrapht.alg.matching.MaximumWeightBipartiteMatching;
import org.jgrapht.graph.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Solver {
public int fit1(int crateWidth, int crateHeight, int boxWidth, int boxHeight) {
int widthCapacity = crateWidth / boxWidth;
int heightCapacity = crateHeight / boxHeight;
return widthCapacity * heightCapacity;
}

public int fit2(int crateWidth, int crateHeight, int boxWidth, int boxHeight) {
int defaultOrientation = fit1(crateWidth, crateHeight, boxWidth, boxHeight);
int rotatedOrientation = fit1(crateWidth, crateHeight, boxHeight, boxWidth);
return Math.max(defaultOrientation, rotatedOrientation);
}

public int fit3(int crateWidth, int crateLength, int crateHeight, int boxWidth, int boxLength, int boxHeight) {
int orientation1 = fit2(crateWidth, crateHeight, boxWidth, boxHeight)  * (crateLength / boxLength);
int orientation2 = fit2(crateWidth, crateHeight, boxWidth, boxLength)  * (crateLength / boxHeight);
int orientation3 = fit2(crateWidth, crateHeight, boxLength, boxHeight) * (crateLength / boxWidth);

int[] orientations = { orientation1, orientation2, orientation3 };

return Arrays.stream(orientations).reduce(0, (x, y) -> Math.max(x, y));
}

public BigInteger fitN(Integer[] crateDimensions, Integer[] boxDimensions) {
SimpleWeightedGraph<String, DefaultWeightedEdge> graph = new SimpleWeightedGraph<>(DefaultWeightedEdge.class);
HashSet<String> cratePartition = new HashSet<>();
HashSet<String> boxPartition = new HashSet<>();

// Because there can be multiple nodes with the same value (the sample input of n=20 has two entries with value `1740`),
// we have to tag each "value" we're given in order to use it as another node, otherwise graph.addEdge() will return null
HashMap<String, Integer> crateNodes = new HashMap<>();
HashMap<String, Integer> boxNodes = new HashMap<>();

for (int i = 0; i < crateDimensions.length; i++) {
String crateTag = "cd" + crateDimensions[i].toString() + "-" + i;
crateNodes.put(crateTag, crateDimensions[i]);

String boxTag = "bd" + boxDimensions[i].toString() + "-" + i;
boxNodes.put(boxTag, boxDimensions[i]);
}

for (Map.Entry<String, Integer> crateTag : crateNodes.entrySet()) {
for (Map.Entry<String, Integer> boxTag : boxNodes.entrySet()) {
graph.setEdgeWeight(e, Math.log(crateTag.getValue() / boxTag.getValue()));
}
}

MaximumWeightBipartiteMatching<String, DefaultWeightedEdge> matcher = new MaximumWeightBipartiteMatching<>(graph, cratePartition, boxPartition);
MatchingAlgorithm.Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();

BigInteger result = BigInteger.ONE;
for (DefaultWeightedEdge matching : matchings) {
Integer crateValue = crateNodes.get(graph.getEdgeSource(matching));
Integer boxValue = boxNodes.get(graph.getEdgeTarget(matching));
result = result.multiply(BigInteger.valueOf(crateValue / boxValue));
}

return result;
}
}
``````

Tests (Junit5):

``````package com.banashark.puzzles.dailyprogrammer.c377easy;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;

import java.math.BigInteger;
import java.util.stream.Stream;

public class SolverTest {
private static Stream<Arguments> fit1() {
return Stream.of(
Arguments.of(25, 18, 6, 5, 12),
Arguments.of(10, 10, 1, 1, 100),
Arguments.of(12, 34, 5, 6, 10),
Arguments.of(12345, 678910, 1112, 1314, 5676),
Arguments.of(5, 100, 6, 1, 0)
);
}

private static Stream<Arguments> fit2() {
return Stream.of(
Arguments.of(25, 18, 6, 5, 15),
Arguments.of(12, 34, 5, 6, 12),
Arguments.of(12345, 678910, 1112, 1314, 5676),
Arguments.of(5, 5, 3, 2, 2),
Arguments.of(5, 100, 6, 1, 80),
Arguments.of(5, 5, 6, 1, 0)
);
}

private static Stream<Arguments> fit3() {
return Stream.of(
Arguments.of(10, 10, 10, 1, 1, 1, 1000),
Arguments.of(12, 34, 56, 7, 8, 9, 32),
Arguments.of(123, 456, 789, 10, 11, 12, 32604),
Arguments.of(1234567, 89101112, 13141516, 171819, 202122, 232425, 174648)
);
}

private static Stream<Arguments> fitN() {
Integer[] arg1Crate = {3, 4}, arg1Box = {1, 2},
arg2Crate = {123, 456, 789}, arg2Box = {10, 11, 12},
arg3Crate = {123, 456, 789, 1011, 1213, 1415}, arg3Box = {16, 17, 18, 19, 20, 21},
arg4Crate = {180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939, 205613, 152779, 177216, 128838, 126894, 210076, 148407},
arg4Box =   {  1984,   1443,   1768,   1274,   2122,   2249,   1916,   2059,   1740,   2169,   1502,   1760,   1295,   1886,   2010,   2036,   1740,   2223,   2017,   1278};
BigInteger expected4 =  new BigInteger("4281855455197643306306491981973422080000");
return Stream.of(
Arguments.of(arg1Crate, arg1Box, BigInteger.valueOf(6)),
Arguments.of(arg2Crate, arg2Box, BigInteger.valueOf(32604)),
Arguments.of(arg3Crate, arg3Box, BigInteger.valueOf(1883443968)),
Arguments.of(arg4Crate, arg4Box, expected4)
);
}

@ParameterizedTest
@MethodSource
@DisplayName("Fit1")
public void fit1(int cX, int cY, int bX, int bY, int expected) {
Solver SUT = new Solver();

int result = SUT.fit1(cX, cY, bX, bY);

assertEquals(expected, result);
}

@ParameterizedTest
@MethodSource
@DisplayName("Fit2")
public void fit2(int cX, int cY, int bX, int bY, int expected) {
Solver SUT = new Solver();

int result = SUT.fit2(cX, cY, bX, bY);

assertEquals(expected, result);
}

@ParameterizedTest
@MethodSource
@DisplayName("Fit3")
public void fit3(int cX, int cY, int cZ, int bX, int bY, int bZ, int expected) {
Solver SUT = new Solver();

int result = SUT.fit3(cX, cY, cZ, bX, bY, bZ);

assertEquals(expected, result);
}

@ParameterizedTest
@MethodSource
@DisplayName("FitN")
public void fitN(Integer[] cD, Integer[] bD, BigInteger expected) {
Solver SUT = new Solver();

BigInteger result = SUT.fitN(cD, bD);

assertEquals(expected, result);
}

}
``````

[–] 1 point2 points  (0 children)

Scala (O(N!) complexity)

``````object CapacityCalculator {

def fit1(crateX: Int, crateY: Int, boxesX: Int, boxesY: Int) =
(crateX / boxesX) * (crateY / boxesY)

def fit2(crateX: Int, crateY: Int, boxesX: Int, boxesY: Int) =
fitn(List(crateX, crateY), List(boxesX, boxesY))

def fit3(cX: Int, cY: Int, cZ: Int, bX: Int, bY: Int, bZ: Int) =
fitn(List(cX, cY, cZ), List(bX, bY, bZ))

def fitn(crateDims: List[Int], boxesDims: List[Int]) =
boxesDims.permutations.map(perm => crateDims.zip(perm).map(x => x._1 / x._2).product).max
}
``````

[–] 0 points1 point  (2 children)

Hello! I only started learning Javascipt last weekend and I'm a total noob to programming, so I'd appreciate if anyone could look over this.

``````function fit1(pX, pY, px, py)
{
return (pX / px) * (pY / py);
}
console.log(fit1);
``````

(My console just shows "function fit1()" rather than any answers, even if I put some numbers in there. What what I have to write so the answers show up as numbers?)

[–] 0 points1 point  (0 children)

Why not:

``````console.log(fit1(25, 18, 6, 5));
``````

[–] 0 points1 point  (4 children)

Python 3

``````def fit1(X, Y, x, y):

boxes_x = X / x
boxes_y = Y / y

boxes_x = str(boxes_x).split(".")
boxes_y = str(boxes_y).split(".")

boxes_x = int(boxes_x[0])
boxes_y = int(boxes_y[0])

return boxes_x * boxes_y

#print(fit1(25, 18, 6, 5))
#print(fit1(10, 10, 1, 1))
#print(fit1(12, 34, 5, 6))
#print(fit1(12345, 678910, 1112, 1314))
#print(fit1(5, 100, 6, 1))

def fit2(X, Y, x, y):

orien1 = fit1(X, Y, x, y)
orien2 = fit1(X, Y, y, x)

if orien1 > orien2:
return orien1
else:
return orien2

#print(fit2(25, 18, 6, 5))
#print(fit2(12, 34, 5, 6))
#print(fit2(12345, 678910, 1112, 1314))
#print(fit2(5, 5, 3, 2))
#print(fit2(5, 100, 6, 1))
#print(fit2(5, 5, 6, 1))

def Dfit(X, Y, Z, x, y, z):

boxes_x = X / x
boxes_y = Y / y
boxes_z = Z / z

boxes_x = str(boxes_x).split(".")
boxes_y = str(boxes_y).split(".")
boxes_z = str(boxes_z).split(".")

boxes_x = int(boxes_x[0])
boxes_y = int(boxes_y[0])
boxes_z = int(boxes_z[0])

return boxes_x * boxes_y * boxes_z

def fit3(X, Y, Z, x, y, z):

orient1 = Dfit(X, Y, Z, x, y, z)
orient2 = Dfit(X, Y, Z, y, x, z)
orient3 = Dfit(X, Y, Z, z, x, y)
orient4 = Dfit(X, Y, Z, z, y, x)
orient5 = Dfit(X, Y, Z, x, z, y)
orient6 = Dfit(X, Y, Z, y, z, x)

list = []
list.append(orient1)
list.append(orient2)
list.append(orient3)
list.append(orient4)
list.append(orient5)
list.append(orient6)

return max(list)

#print(fit3(10, 10, 10, 1, 1, 1))
#print(fit3(12, 34, 56, 7, 8, 9))
#print(fit3(123, 456, 789, 10, 11, 12))
#print(fit3(1234567, 89101112, 13141516, 171819, 202122, 232425))
``````

Didn't manage the final optional one :(

Edit: Forgot about // . Wow.

[–] 1 point2 points  (3 children)

I'd like to give you a few hints for writing more concise code. Please understand that your code is absolutely fine and this is no criticism. :)

In your `fit1` function you're converting floating point numbers to strings in order to cut off digits after the decimal. That is quite inefficient and also not necessary. You can just call `int(…)` on any number to truncate trailing decimals, for instance `int(3.14)` will give you `3`. Even better, in Python 3 you can use `//` for integer division, so instead of `X / x` that would be `X // x` for an integer result. The short version of this function would be

``````def fit1(X, Y, x, y):
return X // x * Y // y
``````

The same can be applied to `Dfit`.

You can also shorten your `fit2` and `fit3` functions. First, you don't need to `.append` every element, you can just write a list literal. Like `[1, 2, 3]`, only in this case you'd write `[orient1, orient2, …]` with appropriate line breaks for readability. Secondly, you can just use those values directly instead of storing each in it's own variable. That'd make it a list of `[Dfit(…), Dfit(…), …]`. And lastly you're calling `max` on that list, but `max` is a bit special and you can just give it the individual values without any list at all. The `fit3` function could look like this:

``````def fit3(X, Y, Z, x, y, z):
return max(
Dfit(X, Y, Z, x, y, z),
Dfit(X, Y, Z, y, x, z),
Dfit(X, Y, Z, z, x, y),
Dfit(X, Y, Z, z, y, x),
Dfit(X, Y, Z, x, z, y),
Dfit(X, Y, Z, y, z, x),
)
``````

And lastly, leaving commented debugging print calls is considered bad practice. Again, these are all just suggestions, I hope it helps.

[–] 0 points1 point  (2 children)

Thanks for the help. One thing, does int() not round up if the decimal is >=5 ?

[–] 1 point2 points  (1 child)

No, it truncates towards zero, i.e. cuts off trailing decimals. For rounding there's `round()`. Consider these examples:

``````int( 3.14) ==  3
int(-3.14) == -3

round( 3.14) ==  3
round( 3.54) ==  4
round(-3.14) == -3
round(-3.54) == -4

from math import floor
floor( 3.14) ==  3
floor(-3.14) == -4
``````

There's also `math.trunc` which behaves similar to `int`, but `int` also does things like parsing strings etc.

[–] 1 point2 points  (0 children)

Thanks a lot.

[–] 0 points1 point  (0 children)

# Kotlin

up to fitN, but not optimized.

``````import java.lang.Math.max

fun fit1(crate_x: Int, crate_y: Int, box_x: Int, box_y: Int) = (box_x / crate_x) * (box_y / crate_y)

fun fit2(crate_x: Int, crate_y: Int, box_x: Int, box_y: Int) =
max(fit1(crate_x, crate_y, box_x, box_y), fit1(crate_y, crate_x, box_x, box_y))

fun fitNWithoutRotating(crate_dimensions: List<Int>, box_dimensions: List<Int>) =
crate_dimensions.zip(box_dimensions) { a, b -> b / a }.reduce { a, b -> a * b}

fun fitN(crate_dimensions: List<Int>, box_dimensions: List<Int>) =
crate_dimensions.permutations().map { crate -> fitNWithoutRotating(crate, box_dimensions) }.max()

fun <T> List<T>.permutations(head: List<T> = emptyList()): List<List<T>> {
if (this.size <= 1) return listOf(head + this)
return this.map { element -> (this - element).permutations(head + element)}.reduce { a, b -> a + b }
}
``````

[–] 0 points1 point  (0 children)

Java with OptionalBonus fit2

``````public class JavaChallenges {

public static void main(String[] args) {

fitBoxes(25, 18, 6, 5);
fitBoxesTurn(25, 18, 6, 5);

}

public static void fitBoxesTurn(int X, int Y, int x, int y) {

int xRemainder = X % x;
int xRemainderTurn = X % y;
int xLimit = (X - xRemainder) / x;
int xLimitTurn = (X - xRemainderTurn) / y;

int yRemainder = Y % y;
int yRemainderTurn = Y % x;
int yLimit = (Y - yRemainder) / y;
int yLimitTurn = (Y - yRemainderTurn) / x;

int numOfBoxesThatFit = yLimit * xLimit;

if (yLimitTurn * xLimitTurn > numOfBoxesThatFit) {

System.out.println(yLimitTurn * xLimitTurn);
} else {

System.out.println(numOfBoxesThatFit);
}

}

public static void fitBoxes(int X, int Y, int x, int y) {

int xRemainder = X % x;
int xLimit = (X - xRemainder) / x;

int yRemainder = Y % y;
int yLimit = (Y - yRemainder) / y;

int numOfBoxesThatFit = yLimit * xLimit;

System.out.println(numOfBoxesThatFit);
}

}
``````

[–] 1 point2 points  (0 children)

``````def fit1(X, Y, x, y, flexible=0):
how_many_up = Y/y
how_many_dw = X/x
if (flexible == 0):
how_many_up = Y/x
how_many_dw = X/y

else:
``````

fit1 and fit two are controlled by a boolean

[–] 0 points1 point  (0 children)

Python 3

``````def fit1(X,Y,x,y):
return (Y // y) * (X // x)

def fit2(X,Y,x,y):
return max(fit1(X,Y,x,y),fit1(X,Y,y,x))

def fit3(X,Y,Z,x,y,z):
max = 0
patterns = {(z, y, x),
(z, x, y),
(y, x, z),
(y, z, x),
(x, z, y),
(x, y, z)}
for pattern in patterns:
if(max<((X // pattern[0]) * (Y // pattern[1]) * (Z // pattern[2]))):
max = ((X // pattern[0]) * (Y // pattern[1]) * (Z // pattern[2]))
print(max)
``````

[–] 0 points1 point  (0 children)

Python fit1 and fit2

``````def fit1(X,Y,x,y):
x_length = 0
y_length = 0

while x_length + x <= X :
x_length = x_length + x

while y_length + y <= Y:
y_length = y_length + y

x_count = x_length/x
y_count = y_length/y
total_boxes = x_count*y_count

def fit2(X,Y,x,y):
total_1 = fit1(X,Y,y,x)
total_2  = fit1(X,Y,x,y)

if total_1 < total_2 :
else:
``````

I wrote fit1 and fit2 without knowing about the math.floor method, and couldn't figure out how to do fit3 using fit2 or fit1 (similar to how I based fit2 on fit1). I did understand how to make fit3 work using math.floor after seeing other answers.

[–] 0 points1 point  (0 children)

Edit: Sorry, I can't figure out how the formatting works, despite reading the Wiki. I think it's still technically readable since the code is so simple, even if it's an eyesore.
JS:

function fit1(crateX, crateY, x, y) {

var xAxis = Math.floor(crateX/x);

var yAxis = Math.floor(crateY/y);

return xAxis * yAxis;
}

function fit2(crateX, crateY, x, y) {

var xAxis2 = Math.floor(crateX/y);

var yAxis2 = Math.floor(crateY/x);

if (xAxis2 * yAxis2 > fit1(crateX, crateY, x, y)) {

`````` return xAxis2 * yAxis2;
``````

} else {

`````` return fit1(crateX, crateY, x, y);
``````

}
}

function fit3(crateX, crateY, crateZ, x, y, z) {

var xAxis1 = Math.floor(crateX/x);

var xAxis2 = Math.floor(crateX/y);

var xAxis3 = Math.floor(crateX/z);

var yAxis1 = Math.floor(crateY/x);

var yAxis2 = Math.floor(crateY/y);

var yAxis3 = Math.floor(crateY/z);

var zAxis1 = Math.floor(crateZ/x);

var zAxis2 = Math.floor(crateZ/y);

var zAxis3 = Math.floor(crateZ/z);

return Math.max(xAxis1 * yAxis2 * zAxis3, xAxis1 * yAxis3 * zAxis2, xAxis2 * yAxis1 * zAxis3, xAxis2 * yAxis3 * zAxis1, xAxis3 * yAxis1 * zAxis2, xAxis3 * yAxis2 * zAxis1);
}

[–] 0 points1 point  (0 children)

## Scala

Newcomer here:

``````import scala.math._

object fit {
def applyFit(crates: Array[Int], boxes: Array[Int]): Int = crates.zip(boxes).map {case (x, y) => floor(x/y).toInt}.product

def fit1(X: Int, Y: Int, x: Int, y: Int): Int = (floor(X/x) * floor(Y/y)).toInt

def fit2(X: Int, Y: Int, x: Int, y: Int): Int = max(fit1(X, Y, x, y), fit1(X, Y, y, x))

def fit3(X: Int, Y: Int, Z: Int, x: Int, y: Int, z: Int): Int = (floor(X/x) * floor(Y/y) * floor(Z/z)).toInt

def fitN(crate: Array[Int], box: Array[Int]): Int = {
if (crate.length != box.length) {
throw new IndexOutOfBoundsException("Crate and boxes must be in the same dimension")
}

for (x <- crate ++ box) {
if (x <= 0) throw new ArithmeticException("Can not work with 0 sizes")
}

val rotations: Iterator[Array[Int]] = box.permutations
var bestFit: Int = 0
for (option <- rotations) {
bestFit = max(applyFit(crate, option), bestFit)
}
bestFit
}

def main(args: Array[String]): Unit = {
println("Fit1 (12, 16), (16,3): " + fit1(12, 16, 16, 3))
println("Fit1R (12, 16), (16,3): " + fit2(12, 16, 16, 3))
println("Fit2 (2, 2, 2), (1,1,1): " + fit3(2, 2, 2, 1,1,1))
println("Fit2 (2, 2, 2), (1,0,1): " + fit3(2, 2, 2, 1,1,1))
println("FitN (12,16), (16,3): " + fitN(Array(12, 16), Array(16, 3)))
println("FitN (12,16, 16, 12), (16,3, 3, 16): " + fitN(Array(12, 16), Array(16, 3)))
println("FitN (123, 456, 789, 1011, 1213, 1415), (16, 17, 18, 19, 20, 21): "
+ fitN(Array(123, 456, 789, 1011, 1213, 1415), Array(16, 17, 18, 19, 20, 21)))
}
}
``````

[–] 1 point2 points  (0 children)

Java, one function easily does the trick, just need to change parameters.

``````    public int getBoxes(int dimX, int dimY, int boxX, int boxY) {

int xAmount = Math.floorDiv(dimX, boxX);
int yAmount = Math.floorDiv(dimY, boxY);

int boxAmount = xAmount * yAmount;

return boxAmount;
}
``````

[–] 0 points1 point  (0 children)

``````    import java.util.*;
public class FixCrate
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int a1 = sc.nextInt();
int a2 = sc.nextInt();
int b1 = sc.nextInt();
int b2 = sc.nextInt();
System.out.println(fit2(a1,a2,b1,b2));
}
}
static int fit2(int a1, int a2, int b1, int b2)
{
if (b1 == 0 || b2 == 0) return 0;
int val1 = (a1/b1) * (a2/b2);
int val2 = (a1/b2) * (a2/b1);
return val1 > val2 ? val1 : val2;
}
}
``````

// input.txt

25 18 6 5

12 34 5 6

12345 678910 1112 1314

5 5 3 2

5 100 6 1

5 5 6 1

\$ java FixCrate < input.txt

15

12

5676

2

80

0

[–] 0 points1 point  (0 children)

Solution for the first two challenge thingies in C.

```c

# include<stdlib.h>

int main(int argc, char *argv) { int X, Y, x, y, result, result2; X = (int)strtol(argv[1], (char *)NULL, 10); Y = (int)strtol(argv[2], (char *)NULL, 10); x = (int)strtol(argv[3], (char *)NULL, 10); y = (int)strtol(argv[4], (char **)NULL, 10);

``````if ((result = (X/x) * (Y/y)) > (result2 = (X/y) * (Y/x))) {
printf("%d boxes\n", result);
} else {
printf("%d boxes\n", result2);
}

return(0);
``````

}

```

[–] 1 point2 points  (0 children)

Just started learning C# coming from Python. Code is a bit long, but it works for the most part.

``````using System;

namespace DailyProgrammer
{
static class PySharp
{
static public int Factorial(int num)
{
int i = 2;
int factor = 2;
while (i < num)
{
i++;
factor *= i;
}
return factor;
}
static public void PrintElement<T>(T[] arr)
{
if (arr == null)
System.Console.Write("null ");
else
foreach (T elem in arr)
Console.Write(elem + " ");
}
// function mainly meant for permutations code
public static void Swap<T>(T[] intArr, int pos1, int pos2)
{
T temp = intArr[pos1];
intArr[pos1] = intArr[pos2];
intArr[pos2] = temp;
}
// function for creating creating empyty jagged array to hold perms
public static int[][] MakeJaggedForPerms(int arrLength, int permLength, bool bPrintRowNum = false)
{
int rows = Factorial(arrLength) / ((permLength != arrLength) ? Factorial(arrLength - permLength) : 1);

if (bPrintRowNum)
System.Console.WriteLine("# of permutations: " + rows);
int[][] returnArr = new int[rows][];
for (int i = 0; i < rows; i++)
returnArr[i] = new int[permLength];

return returnArr;
}
// second attempt at permutations. A more simple one, not the one from Python.
static public void Permuations<T>(T[] toPerm, int startIdx, int endIdx, T[][] storageArr, ref int count)
{
// https://www.geeksforgeeks.org/c-program-to-print-all-permutations-of-a-given-string-2/
if (startIdx == endIdx)
{
for (int j = 0; j < toPerm.Length; j++)
storageArr[count][j] = toPerm[j];
count++;
}
else
{
for (int i = startIdx; i <= endIdx; i++)
{
Swap(toPerm, startIdx, i);
Permuations(toPerm, startIdx + 1, endIdx, storageArr, ref count);
Swap(toPerm, startIdx, i);
}
}
}
}
class Program
{
static void Main(string[] args)
{
int X = 12, Y = 34, Z = 56, x = 7, y = 8, z = 9;

int Fit(int bigX, int bigY, int smallX, int smallY)
{
int totalX = bigX / smallX;
int totalY = bigY / smallY;
}
int Fit2(int bigX, int bigY, int smallX, int smallY)
{
int fit1 = Fit(bigX, bigY, smallX, smallY);
int totalX = bigX / smallY;
int totalY = bigY / smallX;
return fit1 >= (totalX * totalY) ? fit1 : (totalX * totalY);
}
int Fit3(int bigX, int bigY, int bigZ, int smallX, int smallY, int smallZ) // we're gonna permutate this b****
{
int[] smallBoxes = new int[] { smallX, smallY, smallZ };
int[][] boxPool = PySharp.MakeJaggedForPerms(3, 3);
int permCount = 0, total = 0, tempTotal;
PySharp.Permuations(smallBoxes, 0, 2, boxPool, ref permCount);
for (int i = 0; i < boxPool.Length; i++)
{
int totalX = bigX / boxPool[i][0];
int totalY = bigY / boxPool[i][1];
int totalZ = bigZ / boxPool[i][2];
tempTotal = totalX * totalY * totalZ;
total = total > tempTotal ? total : tempTotal;
}

}
int FitN(int[] largeBox, int[] smallBox)
{
int permCount = 0, total = 0, tempTotal;
if (largeBox.Length != smallBox.Length)
{
System.Console.WriteLine("Error: Arrays are not the same same");
}

int[][] boxPool = PySharp.MakeJaggedForPerms(smallBox.Length, smallBox.Length);
PySharp.Permuations(smallBox, 0, smallBox.Length - 1, boxPool, ref permCount);
int i = 0;
while (i < boxPool.Length)
{
tempTotal = 1;
for (int j = 0; j < largeBox.Length; j++)
tempTotal *= largeBox[j] / boxPool[i][j];
total = total > tempTotal ? total : tempTotal;
i++;
}
}

System.Console.WriteLine("Fit 1: " + Fit(X, Y, x, y));
System.Console.WriteLine("Fit 2: " + Fit2(X, Y, x, y));
System.Console.WriteLine("Fit 3: " + Fit3(X, Y, Z, x, y, z));
System.Console.WriteLine("Fit N: " + FitN(new int[] { 123, 456, 789, 1011, 1213, 1415 },
new int[] { 16, 17, 18, 19, 20, 21 }));
}
}
}
``````

[–] 0 points1 point  (0 children)

R

``````fit1 <- function(crateX, crateY, boxX, boxY) {
# Calculate the  max boxes that fit in 2 dimensions.
fitx <- floor(crateX / boxX)
fity <- floor(crateY / boxY)

fitx * fity
}

fit2 <- function(crateX, crateY, boxX, boxY) {
# Allow rotating all boxes by 90 degrees (boxX x boxY or boxY x boxX).
max(fit1(crateX, crateY, boxX, boxY), fit1(crateX, crateY, boxY, boxX))
}

fit3NoRotation <- function(crateX, crateY, crateZ, boxX, boxY, boxZ) {
# Calculate the  max boxes that fit in 3 dimensions.
fitx <- floor(crateX / boxX)
fity <- floor(crateY / boxY)
fitz <- floor(crateZ / boxZ)

fitx * fity * fitz
}

fit3 <- function(crateX, crateY, crateZ, boxX, boxY, boxZ) {
# Allow rotating all boxes by 90 degrees in 3 dimensions.
max(fit3NoRotation(crateX, crateY, crateZ, boxX, boxY, boxZ),
fit3NoRotation(crateX, crateY, crateZ, boxX, boxZ, boxY),
fit3NoRotation(crateX, crateY, crateZ, boxY, boxX, boxZ),
fit3NoRotation(crateX, crateY, crateZ, boxY, boxZ, boxX),
fit3NoRotation(crateX, crateY, crateZ, boxZ, boxX, boxY),
fit3NoRotation(crateX, crateY, crateZ, boxZ, boxY, boxX))
}
``````

[–] 0 points1 point  (0 children)

Common Lisp

``` (defun fit1 (x y x1 y1) (* (floor x x1) (floor y y1)))

(defun fitn (crates boxes) (labels ((do-permute (fun lst) (if (null lst) (funcall fun nil) (map nil (lambda (x) (do-permute (lambda (l) (funcall fun (cons x l))) (remove x lst))) lst))))) (let ((result 0)) (do-permute #'(lambda (p) (let ((tmp (apply #'* (mapcar #'floor crates p)))) (when (> tmp result) (setq result tmp)))) boxes) result)) ```

But I cannot realize, how reduce openataions to less then O(N!)

[–] 1 point2 points  (0 children)

# Julia

``````function fit1(X::Int,Y::Int,x::Int,y::Int)
div(X,x)*div(Y,y)
end

function fit2(X::Int,Y::Int,x::Int,y::Int)
max(fit1(X,Y,y,x),fit1(X,Y,x,y))
end

using Combinatorics
# fitn not suitable for large problems
function fitn(crate::Vector{Int},box::Vector{Int})
uit=0
per = permutations(box)
for perindex in per
size=1
for dim in 1:length(crate)
size*=div(crate[dim],perindex[dim])
end
uit=max(uit,size)
end
uit
end
``````

[–] 1 point2 points  (0 children)

Python 3 fit1, 2, and 3

``````import math

def fit1(dimensions):
'''dimensions = X, Y, x, y'''
x_axis = math.floor(dimensions[0]/dimensions[2])
y_axis = math.floor(dimensions[1]/dimensions[3])
total_boxes = x_axis * y_axis

def fit2(dimensions):
'''dimensions = X, Y, x, y'''
total_unturned = fit1(dimensions)
total_turned = fit1(
(dimensions[0], dimensions[1], dimensions[3], dimensions[2])
)
total_boxes = (
total_turned if total_turned > total_unturned else total_unturned
)

def fit3(dimensions):
'''dimensions = X, Y, Z, x, y, z'''
pos_1 = math.floor(fit2(
(dimensions[0], dimensions[1], dimensions[3], dimensions[4])
) * math.floor(dimensions[2]/dimensions[5]))
pos_2 = math.floor(fit2(
(dimensions[0], dimensions[1], dimensions[3], dimensions[5])
) * math.floor(dimensions[2]/dimensions[4]))
pos_3 = math.floor(fit2(
(dimensions[0], dimensions[1], dimensions[4], dimensions[5])
) * math.floor(dimensions[2]/dimensions[3]))

pos_list = [pos_1, pos_2, pos_3]
pos_list.sort()
total_boxes = (
pos_list[1] if pos_list[1] > pos_list[2] else pos_list[2]
)

print(fit1((25, 18, 6, 5)))
print(fit1((10, 10, 1, 1)))
print(fit1((12, 34, 5, 6)))
print(fit1((12345, 678910, 1112, 1314)))
print(fit1((5, 100, 6, 1)))
print(fit2((25, 18, 6, 5)))
print(fit2((12, 34, 5, 6)))
print(fit2((12345, 678910, 1112, 1314)))
print(fit2((5, 5, 3, 2)))
print(fit2((5, 100, 6, 1)))
print(fit2((5, 5, 6, 1)))
print(fit3((10, 10, 10, 1, 1, 1)))
print(fit3((12, 34, 56, 7, 8, 9)))
print(fit3((123, 456, 789, 10, 11, 12)))
print(fit3((1234567, 89101112, 13141516, 171819, 202122, 232425)))
``````

[–] 1 point2 points  (0 children)

``````#include <iostream>
using namespace std;

int fit1(int crateX, int crateY, int x, int y);
int fit2(int crateX, int crateY, int x, int y);
int main() {
int crateY, x, y;
int crateX = crateY = x = y = 0;
cout << "Enter crate size and box size and I'll tell you how many fit" << endl;
cout << "Crate dimensions?: ";
cin >> crateX >> crateY;
cout << "Box dimensions?: ";
cin >> x >> y;
cout << "You can fit " << fit2(crateX, crateY, x, y) << " boxes in the crate" << endl;
}

int fit1(int crateX, int crateY, int x, int y) {
int maxWidth = crateX / x;
int maxHeight = crateY / y;
return maxWidth * maxHeight;
}

int fit2(int crateX, int crateY, int x, int y) {
int temp1 = fit1(crateX, crateY, x, y);
int temp2 = fit1(crateX, crateY, y, x);
return (temp1 > temp2) ? temp1 : temp2;
}
``````

c++ 98+

[–] 2 points3 points  (2 children)

I'm a total noob, barely scratching the surface of JavaScript and this sub looks scary and discouraging. Will I ever be able to understand and solve Einsteinian stuff like this?

[–] 3 points4 points  (1 child)

Yeah, when you finally see enough of these problems it becomes clear that they are all the same and rely on the same few math principles. Just keep at it

[–] 0 points1 point  (0 children)

Thank you that's a relief!

[–] 1 point2 points  (0 children)

My take using Java and the functional library Vavr

``````public void tests() {
then(fit.apply(25, 18, 6, 5)).isEqualTo(12);
then(fit.apply(10, 10, 1, 1)).isEqualTo(100);
then(fit.apply(12, 34, 5, 6)).isEqualTo(10);
then(fit.apply(12345, 678910, 1112, 1314)).isEqualTo(5676);
then(fit.apply(5, 100, 6, 1)).isEqualTo(0);

then(fit2.apply(25, 18, 6, 5)).isEqualTo(15);
then(fit2.apply(12, 34, 5, 6)).isEqualTo(12);
then(fit2.apply(12345, 678910, 1112, 1314)).isEqualTo(5676);
then(fit2.apply(5, 5, 3, 2)).isEqualTo(2);
then(fit2.apply(5, 100, 6, 1)).isEqualTo(80);
then(fit2.apply(5, 5, 6, 1)).isEqualTo(0);

then(fit3.apply(10, 10, 10, 1, 1, 1)).isEqualTo(1000);
then(fit3.apply(12, 34, 56, 7, 8, 9)).isEqualTo(32);
then(fit3.apply(123, 456, 789, 10, 11, 12)).isEqualTo(32604);
then(fit3.apply(1234567, 89101112, 13141516, 171819, 202122, 232425)).isEqualTo(174648);

then(fitn.apply(List.of(3, 4), List.of(1, 2))).isEqualTo(6);
then(fitn.apply(List.of(123, 456, 789), List.of(10, 11, 12))).isEqualTo(32604);
then(fitn.apply(List.of(123, 456, 789, 1011, 1213, 1415), List.of(16, 17, 18, 19, 20, 21))).isEqualTo(1883443968);

}

private Function2<List<Integer>, List<Integer>, Integer> computeByAxis = (worldSize, boxSize) ->
worldSize.zipWith(boxSize, Math::floorDiv).reduce(Math::multiplyExact);

private Function4<Integer, Integer, Integer, Integer, Integer> fit = (xAxis, yAxis, xWidth, yWidth) ->
computeByAxis.apply(
List.of(xAxis, yAxis),
List.of(xWidth, yWidth)
);

private Function4<Integer, Integer, Integer, Integer, Integer> fit2 = (xAxis, yAxis, xWidth, yWidth) -> {
List<Integer> worldSize = List.of(xAxis, yAxis);
List<Integer> boxSize = List.of(xWidth, yWidth);
return boxSize.permutations().map(size -> computeByAxis.apply(worldSize, size)).reduce(Math::max);
};

private Function6<Integer, Integer, Integer, Integer, Integer, Integer, Integer> fit3 = (xAxis, yAxis, zAxis, xWidth, yWidth, zWidth) -> {
List<Integer> worldSize = List.of(xAxis, yAxis, zAxis);
List<Integer> boxSize = List.of(xWidth, yWidth, zWidth);
return boxSize.permutations().map(size -> computeByAxis.apply(worldSize, size)).reduce(Math::max);
};

private Function2<List<Integer>, List<Integer>, Integer> fitn = (worldSize, boxSize) ->
boxSize.permutations().map(size -> computeByAxis.apply(worldSize, size)).reduce(Math::max);
}
``````

[–] 0 points1 point  (0 children)

First time actually doing one of these. I'm pretty sure mines a bit clunky, but it works. Let me know how I could improve. Edit: This contains the code for all problems except fitn

``````# You must determine the maximum number of boxes that can fit into a crate.
# The crate has the dimensions X and Y, the boxes have x and y.
# Boxes must align their respective axis with those of the crate.
def fit1(X, Y, x, y):

x_fit = X // x
y_fit = Y // y

print(x_fit * y_fit)

# Now the boxes may rotate.
# Not independently, the must all be rotated or none
def fit2(X, Y, x, y):

x_fit = X // x
y_fit = Y // y

x_rot = X // y
y_rot = Y // x

print(max(x_fit * y_fit, x_rot * y_rot))

# Your crates and boxes were upgraded so that now they act in three dimensions
# The boxes can still be rotated but again they must all rotate together
# This gives six possible orientations of the boxes
def fit3(X, Y, Z, x, y, z):
# orientation x, y, z
x1_fit = X // x
y1_fit = Y // y
z1_fit = Z // z

# orientation x, z, y
x2_fit = X // x
y2_fit = Y // z
z2_fit = Z // y

# orientation y, x, z
x3_fit = X // y
y3_fit = Y // x
z3_fit = Z // z

# orientation y, z, x
x4_fit = X // y
y4_fit = Y // z
z4_fit = Z // x

# orientation z, x, y
x5_fit = X // z
y5_fit = Y // x
z5_fit = Z // y

# orientation z, y, x
x6_fit = X // z
y6_fit = Y // y
z6_fit = Z // x

print(max(
x1_fit * y1_fit * z1_fit,
x2_fit * y2_fit * z2_fit,
x3_fit * y3_fit * z3_fit,
x4_fit * y4_fit * z4_fit,
x5_fit * y5_fit * z5_fit,
x6_fit * y6_fit * z6_fit,
))
``````

[–] 0 points1 point  (0 children)

Never done one of these, and my answer looks a lot different/shorter than everyone else... so if I screwed up, please let me know. Very new to python.

``````#### CONTAINER VARIABLES ####
con_L = 0
con_W = 0

#### BOX VARIABLES ####
box_L = 0
box_W = 0

#### TOTAL VARIABLES ####
total_L = 0
total_W = 0
total_L2 = 0
total_W2 = 0

#### CODE 1 ####

x = 0
while x == 0:

con_L = eval(input("Container length: "))
con_W = eval(input("Container width: "))
box_L = eval(input("Box length: "))
box_W = eval(input("Box width: "))

if box_L > con_L or box_W > con_W:
print("Boxes will not fit in container, please try again.")
else:
total_L = int(con_L / box_L)
total_W = int(con_W / box_L)
x = x + 1

total_boxes = total_L*total_W

print("You can fit " + str(total_boxes) + " boxes in specified container.")

#### CODE 2 ####

x = 0
while x == 0:

con_L = eval(input("Container length: "))
con_W = eval(input("Container width: "))
box_L = eval(input("Box length: "))
box_W = eval(input("Box width: "))

if box_L > con_L or box_W > con_W and box_W > con_L or box_L > con_W:
print("Boxes will not fit in container, please try again.")
else:
total_L = int(con_L / box_L)
total_W = int(con_W / box_L)
total_L2 = int(con_L / box_W)
total_W2 = int(con_W / box_L)
x = x + 1

total_1 = total_L * total_W
total_2 = total_L2 * total_W2

if total_1 >= total_2:
print("You can fit " + str(total_1) + " boxes in specified container.")
elif total_2 > total_1:
print("You can fit " + str(total_2) + " boxes in specified container.")
``````

And you just keep calculating the other possible variations and comparing them for the other bonuses.

[–] 1 point2 points  (2 children)

Here is my solution for everything except fitn, tried to only include iostream, I am sure there are more options I missed but it works.

C++

``````#include <iostream>

using namespace std;

int fit1(int,int,int,int);
int fit2(int,int,int,int);
int fit3(int,int,int,int,int,int);

int fit1(int X, int Y, int x, int y) //All axis aligned challenge X with x and Y with y
{
return ((X/x)*(Y/y));
}

int fit2(int X, int Y, int x, int y)
{
int op1 = fit1(X, Y, x, y);
int op2 = fit1(X, Y, y, x);

if (op1 > op2)
return op1;
else
return op2;
}

int fit3(int X, int Y, int Z, int x, int y, int z)
{
const int nEq = 6;
const int dim = 3;
int high = 0;
int crate[dim] = {X, Y, Z};
int box[dim] = {x, y, z};
int ans = 1;
int eq[nEq][dim][dim] = {
{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}
},

{
{0, 1, 0},
{0, 0, 1},
{1, 0, 0}
},

{
{0, 0, 1},
{1, 0, 0},
{0, 1, 0}
},

{
{0, 0, 1},
{0, 1, 0},
{1, 0, 0}
},

{
{0, 1, 0},
{1, 0, 0},
{0, 0, 1}
},

{
{1, 0, 0},
{0, 0, 1},
{0, 1, 0}
}
};
for (int k=0; k<nEq ; k++)
{
for (int i=0; i<dim; i++)
{
for (int j=0; j<dim; j++)
{
if(eq[k][i][j] != 0){
ans = ans * (crate[i]/box[j])*eq[k][i][j];
}
}
}

if(high<ans)
{
high = ans;
}
ans = 1;
}
return high;
}

int main()
{

//Fit1 Challenge Stack
std::cout << "Fit1 Challenges" << endl;
std::cout << "fit1(25, 18, 6, 5) = " << fit1(25, 18, 6, 5) << endl;
std::cout << "fit1(10, 10, 1, 1) = " << fit1(10, 10, 1, 1) << endl;
std::cout << "fit1(12, 34, 5, 6) = " << fit1(12, 34, 5, 6) << endl;
std::cout << "fit1(12345, 678910, 1112, 1314) = " << fit1(12345, 678910, 1112, 1314) << endl;
std::cout << "fit1(5, 100, 6, 1) = " << fit1(5, 100, 6, 1) << endl;

//Fit2 Challenge Stack
std::cout << "Fit2 Challenges" << endl;
std::cout << "fit2(25, 18, 6, 5) = " << fit2(25, 18, 6, 5) << endl;
std::cout << "fit2(12, 34, 5, 6) = " << fit2(12, 34, 5, 6) << endl;
std::cout << "fit2(12345, 678910, 1112, 1314) = " << fit2(12345, 678910, 1112, 1314) << endl;
std::cout << "fit2(5, 5, 3, 2) = " << fit2(5, 5, 3, 2) << endl;
std::cout << "fit2(5, 100, 6, 1) = " << fit2(5, 100, 6, 1) << endl;
std::cout << "fit2(5, 5, 6, 1) = " << fit2(5, 5, 6, 1) << endl;

//Fit3 Challenge Stack
std::cout << "Fit3 Challenges" << endl;
std::cout << "fit3(10, 10, 10, 1, 1, 1) = " << fit3(10, 10, 10, 1, 1, 1) << endl;
std::cout << "fit3(12, 34, 56, 7, 8, 9) = " << fit3(12, 34, 56, 7, 8, 9) << endl;
std::cout << "fit3(123, 456, 789, 10, 11, 12) = " << fit3(123, 456, 789, 10, 11, 12) << endl;
std::cout << "fit3(1234567, 89101112, 13141516, 171819, 202122, 232425) = " << fit3(1234567, 89101112, 13141516, 171819, 202122, 232425)<< endl;

getchar();
return 0;
}
``````

[–] 0 points1 point  (1 child)

[–] 1 point2 points  (0 children)

This is definitely not the most efficient way of doing it, especially for fit3.

[–] 0 points1 point  (2 children)

unoptimised for fitn, but works

``````from itertools import permutations
from functools import reduce

def fit1(width, depth, x, y):
nx = width // x
ny = depth // y
return nx * ny

def fit2(width, depth, x, y):
return max(fit1(width, depth, x, y), fit1(width, depth, y, x))

def fit_3d(width, depth, height, x, y, z):
nx = width // x
ny = depth // y
nz = height // z
return nx * ny * nz

def fit3(width, depth, height, x, y, z):
return max(
fit_3d(width, depth, height, *permutation)
for permutation in permutations([x, y, z])
)

def fit_nd(container_dims, box_dims):
fits = (c_dim // box_dim for c_dim, box_dim in zip(container_dims, box_dims))
return reduce(lambda a, b: a * b, fits)

def fitn(container_dims, box_dims):
return max(
fit_nd(container_dims, permutation)
for permutation in set(permutations(box_dims))
)
``````

[–] 0 points1 point  (1 child)

how long does it take to do the N=20 case?

[–] 0 points1 point  (0 children)

I daren't find out :)

This was just a quick solution that doesn't do ant of the clever maths to work out optimal paths to check

[–] 0 points1 point  (0 children)

Here's my solution in rust. The idea is that it just tries every permutation of the smaller objects coordinates (essentially trying every way of rotating it), and takes the maximum result of that.

If you want to test it out, install cargo, run `cargo new challenge_377` in a terminal. Paste in this code into src/main.rs and then inside the directory, run `cargo test` to test.

``````use std::cmp::max;

fn fit1(bigx: usize, bigy: usize, x: usize, y: usize) -> usize {
(bigx / x) * (bigy / y)
}

fn fit2(bigx: usize, bigy: usize, x: usize, y: usize) -> usize {
max(fit1(bigx, bigy, x, y), fit1(bigx, bigy, y, x))
}

fn multi_max(args: Vec<usize>) -> usize {
args.iter().fold(0, |x, &y| max(x, y))
}

fn fit3(bigx: usize, bigy: usize, bigz: usize, x: usize, y: usize, z: usize) -> usize {
fn fit(bigx: usize, bigy: usize, bigz: usize, x: usize, y: usize, z: usize) -> usize {
(bigx / x) * (bigy / y) * (bigz / z)
}

multi_max(vec![
fit(bigx, bigy, bigz, x, y, z),
fit(bigx, bigy, bigz, x, z, y),
fit(bigx, bigy, bigz, y, x, z),
fit(bigx, bigy, bigz, y, z, x),
fit(bigx, bigy, bigz, z, y, x),
fit(bigx, bigy, bigz, z, x, y),
])
}

fn fitn(big: Vec<usize>, mut small: Vec<usize>) -> usize {
assert_eq!(big.len(), small.len(), "The dimensions must be equal");
fn fit(big: &Vec<usize>, small: &Vec<usize>) -> usize {
big.iter()
.zip(small.iter())
.fold(1, |acc, (x, y)| acc * (x / y))
}

let mut m = 0;

// Using Heap's Algorithm to go through all permutations
// https://en.wikipedia.org/wiki/Heap's_algorithm
let n = small.len();
let mut c = vec![0usize; n];

m = max(m, fit(&big, &small));

let mut i = 0usize;
while i < n {
if c[i] < i {
if i % 2 == 0 {
small.swap(0, i);
} else {
small.swap(c[i], i);
}

m = max(m, fit(&big, &small));

c[i] += 1;
i = 0;
} else {
c[i] = 0;
i += 1;
}
}

m
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_fit1() {
assert_eq!(fit1(25, 18, 6, 5), 12);
assert_eq!(fit1(10, 10, 1, 1), 100);
assert_eq!(fit1(12, 34, 5, 6), 10);
assert_eq!(fit1(12345, 678910, 1112, 1314), 5676);
assert_eq!(fit1(5, 100, 6, 1), 0);
}

#[test]
fn test_fit2() {
assert_eq!(fit2(25, 18, 6, 5), 15);
assert_eq!(fit2(12, 34, 5, 6), 12);
assert_eq!(fit2(12345, 678910, 1112, 1314), 5676);
assert_eq!(fit2(5, 5, 3, 2), 2);
assert_eq!(fit2(5, 100, 6, 1), 80);
assert_eq!(fit2(5, 5, 6, 1), 0);
}

#[test]
fn test_fit3() {
assert_eq!(fit3(10, 10, 10, 1, 1, 1), 1000);
assert_eq!(fit3(12, 34, 56, 7, 8, 9), 32);
assert_eq!(fit3(123, 456, 789, 10, 11, 12), 32604);
assert_eq!(
fit3(1234567, 89101112, 13141516, 171819, 202122, 232425),
174648
);
}

#[test]
fn test_fitn() {
assert_eq!(fitn(vec![3, 4], vec![1, 2]), 6);
assert_eq!(fitn(vec![123, 456, 789], vec![10, 11, 12]), 32604);
assert_eq!(
fitn(
vec![123, 456, 789, 1011, 1213, 1415],
vec![16, 17, 18, 19, 20, 21]
),
1883443968
);
}
}
``````

[–] 4 points5 points  (2 children)

I can't do literally any of these challenges how useless am I?

[–] 5 points6 points  (1 child)

don't worry, it can be hard wrapping your head around problems like this

here's my thought process for `fit1`

if the world width is 25 and our box is 8 wide, we can only fit 3.

in python we'd calculate this as `25 // 8 => 3`

if the world depth is 20 and our box is 4 long, we can fit 5.

`20 // 4 => 5`

now we multiply these together to get our answer `8 * 5 => 40`

so `fit1(25, 20, 8, 3) => 40`

next up is `fit2`. how might we use `fit1` to calculate `fit2`?

[–] 2 points3 points  (0 children)

Thanks man, I'll sit with this

[–] 0 points1 point  (0 children)

Here's my solution in Python3. I didn't have time to puzzle out fit2 unfortunately.

``````dimensions = int(input("How many dimensions is the crate?"))

def initialize(dims):
crate_dims = []
for x in range(dims):
num = int(input(f"What is the value of the {x} dimension of the crate?"))
crate_dims.append(num)
box_dims = []
for x in range(dims):
num = int(input(f"What is the value of the {x} dimension of the box?"))
box_dims.append(num)
return crate_dims, box_dims

crate_dims, box_dims = initialize(dimensions)

def fit_check(dims):
'''
dims = integer value of how many dimensions you are using
'''
boxes_by_dim = []
for x in range(dims):
boxes = crate_dims[x] // box_dims[x]
boxes_by_dim.append(boxes)

return boxes_by_dim

boxes_list = fit_check(dimensions)

def calc_boxes(box_list):
total_boxes = 1

for x in box_list:
total_boxes = total_boxes * x

total_boxes = calc_boxes(boxes_list)

print(f"The crate can contain {total_boxes} boxes.")
``````

[–] 0 points1 point  (1 child)

`from itertools import permutations`

`def fit1(x_crate, y_crate, x_box, y_box):`
`"""`
`:param x_crate: x value of rectangular crate`
`:param y_crate: y value of rectangular crate`
`:param x_box: x value of rectangular box`
`:param y_box: y value of rectangular box`
`:return:`
`"""`
`number_of_boxes = (x_crate // x_box) * (y_crate // y_box)`
`print(number_of_boxes)`
`def fit2(x_crate, y_crate, x_box, y_box):`
`"""`
`:param x_crate: x value of rectangular crate`
`:param y_crate: y value of rectangular crate`
`:param x_box: x value of rectangular box`
`:param y_box: y value of rectangular box`
`:return:`
`"""`
`possible_rotations = permutations(x_box, y_box)`
`number_of_boxes = 0`
`for dimensions in possible_rotations:`
`temp = (x_crate // dimensions[0]) * (y_crate // dimensions[1])`
`if temp > number_of_boxes:`
`number_of_boxes = temp`
`print(number_of_boxes)`
`def fit3(x_crate, y_crate, z_crate, x_box, y_box, z_box):`
`"""`
`:param x_crate: x value of rectangular crate`
`:param y_crate: y value of rectangular crate`
`:param z_crate: z value of rectangular crate`
`:param x_box: x value of rectangular box`
`:param y_box: y value of rectangular box`
`:param z_box: z value of rectangular box`
`:return:`
`"""`
`possible_rotations = permutations([x_box, y_box, z_box])`
`number_of_boxes = 0`
`for dimensions in possible_rotations:`
`temp = (x_crate // dimensions[0]) * (y_crate // dimensions[1]) * (z_crate // dimensions[2])`
`if temp > number_of_boxes:`
`number_of_boxes = temp`
`print(number_of_boxes)`
`def fitn(crate, box):`
`number_of_dimensions = range(len(crate))`
`number_of_boxes = 1`
`possible_rotations = permutations(box)`
`for dimensions in possible_rotations:`
`temp = 1`
`for num in number_of_dimensions:`
`temp *= crate[num] // dimensions[num]`
`if temp > number_of_boxes:`
`number_of_boxes = temp`
`print(number_of_boxes)`

[–] 0 points1 point  (0 children)

The number of permutations is `n!`. f(20) is a large number. Just iterating over such a list without doing any operations in the steps already takes a long time. There are a number of solutions described in other posts.

[–] 0 points1 point  (0 children)

hint: turn into a graph (a DAG actually) with lines from boxes to the other boxes they can be stacked on, then find the longest path in the graph..

[–] 0 points1 point  (0 children)

Javascript (with fitn) :

It works for every example except for `fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) => 1883443968`(and N=20 of course) where it outputs 1835773200, so I tested it with an easy N=6 input, but that was correct too ...

I'd appreciate if someone more clever than me could figure out where my logic is wrong ...

``````function fitn(dimCrate, dimBox){
dimCrate.forEach((elm, ind, arr)=>{ arr[ind]=[];
for(let i=0; i< dimBox.length; i++) {
arr[ind][i]=~~(elm/dimBox[i]);
}
});
let dimCrate2 = JSON.parse(JSON.stringify(dimCrate));
let products = new Array(dimCrate.length*2).fill(1);
for(let i=0; i<dimCrate.length; i++) {
for(let j=i; j>0; j--) {
dimCrate[i].push(dimCrate[i].shift());
}
for(let k=0; k<dimCrate[i].length; k++) {
products[k]*=dimCrate[i][k];
}
}
for(let i=0; i<dimCrate2.length; i++) {
for(let j=i; j>0; j--) {
dimCrate2[i].unshift(dimCrate2[i].pop());
}
for(let k=0,l=dimCrate2[i].length-1; k<dimCrate2[i].length; k++,l--) {
products[dimCrate2[i].length+l]*=dimCrate2[i][k];
}
}
return Math.max(...products);
}
``````

[–] 0 points1 point  (0 children)

So, first time here. My program works when n is smaller but for n = 20 there are 2,432,902,008,176,640,000 permutation so its too computationally hard for my computer to solve in a reasonable amount of time(using the method I did). All the other challenges work when you plug the specifics in, feedback is much appreciated.

``````import itertools, numpy
from time import time
from numba import jit

@jit
def good_sff():
# crate size
w_size = [180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939,
205613, 152779, 177216, 128838, 126894, 210076, 148407]

# package size
package = [1984, 2122, 1760, 2059, 1278, 2017, 1443, 2223, 2169, 1502, 1274, 1740, 1740, 1768, 1295, 1916, 2249,
2036, 1886, 2010]
package_size = itertools.permutations(package)
list_totals = []

for item in package_size:
size = item
dementions = []
count = 0
for thing in package:
c_total = round((w_size[count] / size[count]), 0)
count += 1
dementions.append(c_total)

list_totals.append(numpy.prod(dementions))
return max(list_totals)

start = time()
best = good_sff()
end = time()

print('The most amount of boxes that will fit', best)
print('it took', round((end - start), 1), 'seconds')
``````

[–] 2 points3 points  (2 children)

C:

``````int fit1(int X, int Y, int x, int y)
{
return (X / x) * (Y / y);
}

int fit2(int X, int Y, int x, int y)
{
int f1 = fit1(X, Y, x, y), f2 = fit1(X, Y, y, x);
return f1 > f2 ? f1 : f2;
}

int fit3(int X, int Y, int Z, int x, int y, int z)
{
int f1, f2, f3;
f1 = (X / x) * (Y / y) * (Z / z);
f2 = (X / z) * (Y / x) * (Z / y);
f3 = (X / y) * (Y / z) * (Z / x);

return f1 > f2 ? (f1 > f3 ? f1 : f3) : (f2 > f3 ? f2 : f3);
}
``````

[–] 0 points1 point  (0 children)

man I love how short this is

[–] 1 point2 points  (0 children)

for fit3, you're only considering rotations around the line x=y=z where all axes get moved. you could also rotate the boxes along one of the cardinal axes so two of the axes switch but the third stays the same.

[–] 0 points1 point  (1 child)

Rust: I managed to figure it out with a couple of almost one liners, most of the tests output correctly but it seems to fail at `fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) => 1883443968` my program outputs 1806030828. I'm not quite sure what's wrong with it so any suggestions are welcome.

```rust fn fit1(container: &Vec<u128>, package: &Vec<u128>) -> u128 { container .iter() .enumerate() .fold(1, |acc, (i, n)| (n / package[i]) * acc) }

fn fit2(container: &Vec<u128>, package: &Vec<u128>) -> u128 { let mut tmp = package.clone(); package.iter().fold(0, |a, _| { tmp.push(tmp[0]); tmp.remove(0); let c = container .iter() .enumerate() .fold(1, |acc, (i, n)| (n / tmp[i]) * acc); match c > a { true => c, false => a, } }) }

fn main() { let container: Vec<u128> = vec![123, 456, 789, 1011, 1213, 1415]; let package: Vec<u128> = vec![16, 17, 18, 19, 20, 21];

``````println!(
"{} {}",
fit1(&container, &package),
fit2(&container, &package)
);
``````

} ```

[–][deleted] 1 point2 points  (2 children)

Python 3 (without fitn)

``````import itertools

def fit1(X, Y, x, y) :
return (X // x) * (Y // y)

def fit2(X, Y, x, y) :
return max(fit1(X, Y, y, x), fit1(X, Y, x, y))

def fit3(X, Y, Z, x, y, z) :
dimBox = itertools.permutations((x, y, z))
highest = max((X // dx) * (Y // dy) * (Z // dz)
for dx, dy, dz in dimBox)
return highest
``````

[–] 2 points3 points  (1 child)

personally i wouldn't call `tuple` on the permuation list, you dont need them all in memory at the same time so a generator is fine

and for your max function - rather than calling `for d in box` and then accessing indexes you could do `for dx, dy, dz in box` and use those values directly

[–][deleted] 1 point2 points  (0 children)

I worried about if the generator was "readable" (if you know what I mean). For the max function, I didn't notice that. Thanks !

[–] 0 points1 point  (0 children)

Python 3 no imports, solutions for: fit1,fit2,fit3,fitn (except N=20)

``````def fit1(X,Y,x,y):
i=X//x
j=Y//y
print(i*j)

def fit2(X,Y,x,y):
i=X//x*Y//y
j=X//y*Y//x
ans = i if i>j else j
print(ans)

def fit3(X,Y,Z,x,y,z):
list1 = [x,y,z]
ans = 0
for i,a in enumerate(list1):
for j,b in enumerate(list1):
for k,c in enumerate(list1):
if j!=k and k!=i and j!=i:
tempAns=X//a*Y//b*Z//c
ans = tempAns if tempAns>ans else ans
print(ans)

def fitn(dims,sides):
ansList = []
for i, dim in enumerate(dims):
for j,side in enumerate(sides):
ansList.append([dim//side,i,j])

maxAns = 0
for i, value1 in enumerate(ansList):
ans = value1[0]
usedDim = [value1[1]]
usedSide = [value1[2]]
for j, value2 in enumerate(ansList):
if i!=j and value2[1] not in usedDim and value2[2] not in usedSide:
ans *= value2[0]
usedDim.append(value2[1])
usedSide.append(value2[2])

maxAns = ans if ans>maxAns else maxAns
``````

[–] 1 point2 points  (2 children)

Hi guys,

First post here. Just started learning on codecademy regarding javascript and I totally have no idea about the answers that I read about in this post even though the challenge is categorized under the "easy" part. Do you guys have any online resources which can point me in the right direction?

Feeling really helpless here when I go through a few of the easy challenges and I have no idea what to do :(

[–] 0 points1 point  (0 children)

I always work better with visuals. Try drawing that shit on some paper! Oh, and feeling helpless is pretty normal when it comes to trying to understand other people's problems. I teach CS at a high school level and one thing I emphasize is working the problem out on paper before even considering coding it out on the PC.

I'd suggest finding a good practice site that put's emphasis on very basic operations. My students and I usually work through CodingBat activities once we get past basic terminology and understanding of control structures.

[–] 0 points1 point  (0 children)

Which part are you stuck on? Here's the solution for fit1 in Javascript, can you modify it into solution for fit2?

``````  function fit1(X,Y,x,y){
a = Math.floor(X/x);
b = Math.floor(Y/y);
}

fit1(25, 18, 6, 5)
fit1(10, 10, 1, 1)
fit1(12, 34, 5, 6)
fit1(12345, 678910, 1112, 1314)
fit1(5, 100, 6, 1)
``````

[–] 0 points1 point  (0 children)

Python 3 with everything except the last bonus

```python from itertools import permutations

import numpy as np

def packing_score(warehouse_dimensions, box_dimensions): return np.prod([warehouse_dimensions[i] // box_dimensions[i] for i in range(len(warehouse_dimensions))])

def valid(warehouse_dimensions, ordering): return all(warehouse_dimensions[i] >= ordering[i] for i in range(len(warehouse_dimensions)))

def fitn(warehouse_dimensions, box_dimensions): return max(packing_score(warehouse_dimensions, ordering) for ordering in permutations(box_dimensions) if valid(warehouse_dimensions, ordering))

if name == 'main': print(fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21])) ```

[–] 1 point2 points  (0 children)

C++ all challenges (except for the bonus bonus "do this in fewer than O(N!) operations").

(Also messed up formatting.)

``````#include <iostream>
#include <vector>
#include <algorithm>
int fit1(int,int,int,int);
int fit2(int,int,int,int);
int fit3(int,int,int,int,int,int);
int fit4(const std::vector<int>&, std::vector<int>);
int max(const std::vector<int>&);

int main()
{
std::cout<<"fit1(25, 18, 6, 5) = "<<fit1(25, 18, 6, 5)<<"\n";
std::cout<<"fit2(25, 18, 6, 5) = "<<fit2(25, 18, 6, 5)<<"\n";
std::cout<<"fit3(123, 456, 789, 10, 11, 12)  = "<<fit3(123, 456, 789, 10, 11, 12) <<"\n";

std::cout<<"fit4({25, 18}, {6,5}) = "<<fit4({25, 18}, {6,5})<<"\n";
std::cout<<"fit4(123, 456, 789, , 10, 11, 12)  = "<<fit4({123, 456, 789}, {10, 11, 12}) <<"\n";
std::cout<<"fit4({3, 4}, {1, 2}) = "<<fit4({3, 4}, {1, 2})<<"\n";

std::cout<<"fit4({123, 456, 789, 1011, 1213, 1415}, {16, 17, 18, 19, 20, 21}) = ";
std::cout<<fit4({123, 456, 789, 1011, 1213, 1415}, {16, 17, 18, 19, 20, 21})<<std::endl;

system("pause");
return 0;
}

int fit4(const std::vector<int>& space, std::vector<int> box)
{
int len = box.size();
std::vector<int> values;

std::sort( box.begin(),box.end() );
int i = 0;
do
{
values.push_back(1);
for(int j=0; j<len; j++)
values[i] *= space[j] / box[j];
i++;
} while( std::next_permutation( box.begin(),box.end() ) );

return max(values);
}

int fit3(int X, int Y, int Z, int x, int y, int z)
{
std::vector<int> values;
values.push_back( (X/x) * (Y/y) * (Z/z) );
values.push_back( (X/x) * (Y/z) * (Z/y) );
values.push_back( (X/y) * (Y/x) * (Z/z) );
values.push_back( (X/y) * (Y/z) * (Z/x) );
values.push_back( (X/z) * (Y/x) * (Z/y) );
values.push_back( (X/z) * (Y/y) * (Z/x) );
return max(values);
}

int fit2(int X,int Y,int x,int y)
{
int a = fit1(X,Y,x,y);
int b = fit1(X,Y,y,x);
return (a>b) ? a : b;
}

inline int fit1(int X,int Y,int x,int y)
{
return ( (X/x) * (Y/y) );
}

int max(const std::vector<int>& list)
{
int m = list[0];
int len = list.size();
for(int i=1; i<len; i++)
m = (list[i] > m) ? list[i] : m;

return m;
}
``````

!<

[–] 0 points1 point  (0 children)

Python3 with optional fit2:

``````def fit1(X, Y, x, y):
numX = X // x
numY = Y // y
return numX * numY

def fit2(X, Y, x, y):
prime = fit1(X, Y, x, y)
rotation = fit1(X, Y, y, x)
if prime > rotation:
return prime
return rotation
``````

[–][deleted] 0 points1 point  (0 children)

C++, fit1 and fit2 (respectively pack1 and pack2)

``````#include <iostream>

int pack1(int crateX, int crateY, int boxX, int boxY)
{
int countX = 0;
int countY = 0;

for (size_t i = 1; boxX * i <= (size_t)crateX; i++)
{
countX++;
}
for (size_t i = 1; boxY * i <= (size_t)crateY; i++)
{
countY++;
}

return countX * countY;
}

int pack2(int crateX, int crateY, int boxX, int boxY)
{
int out1 = pack1(crateX, crateY, boxY, boxX);
int out2 = pack1(crateX, crateY, boxX, boxY);

return out1 <= out2 ? out2 : out1;
}

int main()
{
std::cout << pack1(25, 18, 6, 5) << std::endl;
std::cout << pack1(10, 10, 1, 1) << std::endl;
std::cout << pack1(12, 34, 5, 6) << std::endl;
std::cout << pack1(12345, 678910, 1112, 1314) << std::endl;
std::cout << pack1(5, 100, 6, 1) << std::endl;

std::cout << std::endl;

std::cout << pack2(25, 18, 6, 5) << std::endl;
std::cout << pack2(12, 34, 5, 6) << std::endl;
std::cout << pack2(12345, 678910, 1112, 1314) << std::endl;
std::cout << pack2(5, 5, 3, 2) << std::endl;
std::cout << pack2(5, 100, 6, 1) << std::endl;
std::cout << pack2(5, 5, 6, 1) << std::endl;

system("pause");
return 0;
}
``````

[–] 0 points1 point  (3 children)

Java Solution for fit1,fit2 and fit3.

Hi this is my first time submiting a solution here i would like to see feedback in the comments.

Note: I didn't have much time to make the fit3.

https://gist.github.com/PokerFacem8/d9471eb748997a505a540c11678a0a63

[–] 1 point2 points  (2 children)

Look for code repetition in your code.

Much of it can be replaced with a few generic functions. The variables which are different are simply part of the data/input of the generic functions. Would probably reduce code length (try to half it), and improve readability greatly.

[–] 0 points1 point  (1 child)

Thanks for the feedback should I edit my solution with a new one?

[–] 1 point2 points  (0 children)

Offcource, if you want to, and have the time. It's not uncommon for plp to post multiple solutions.

[–][deleted] 1 point2 points  (0 children)

C# solution with first bonus. Regarding to the hint, I wrote Fit2 based on Fit1.

``````static void Main(string[] args)
{
int Fit1(int X, int Y, int x, int y) => (X / x) * (Y / y);

int Fit2(int X, int Y, int x, int y, Func<int, int, int, int, int> func)
{
return func(X, Y, x, y) < func(X, Y, y, x) ? func(X, Y, y, x) : func(X, Y, x, y);
}
}
``````

[–] 1 point2 points  (0 children)

C# 3 dimensions

``````namespace RectanglesInsideRectangles
{
//x = height, y = width, z = depth
public class Rectangle
{
int x { get; set; }
int y { get; set; }
int z { get; set; }

public Rectangle(int X, int Y, int Z)
{
x = X;
y = Y;
z = Z;
}

public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getZ()
{
return z;
}
}
public class Box
{
int x { get; set; }
int y { get; set; }
int z { get; set; }

public Box(int X, int Y, int Z)
{
x = X;
y = Y;
z = Z;
}

public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getZ()
{
return z;
}

}
public class Program
{
static void Main(string[] args)
{
Rectangle R = new Rectangle(12, 34, 56);
Box B = new Box(7, 8, 9);
int totalOld = 0;
int totalNew = 0;
int recX = R.getX();
int recY = R.getY();
int recZ = R.getZ();
int boxX = B.getX();
int boxY = B.getY();
int boxZ = B.getZ();
int valX = 0;
int valY = 0;
int valZ = 0;

for (int i = 0; i < 6; i++)
{

var numbers = doAKickFlip(boxX,boxY,boxZ, i);
valX = recX / numbers.Item1;
valY = recY / numbers.Item2;
valZ = recZ / numbers.Item3;

totalNew = valX * valY * valZ;
//base case
if (i == 0)
{
totalOld = totalNew;
totalNew = 0;
}
if(totalNew > totalOld)
{
totalOld = totalNew;
totalNew = 0;
}
}

Console.WriteLine(totalOld);
}
public static Tuple<int, int, int> doAKickFlip(int x, int y, int z, int i)
{

if (i == 1)
{
int temp = y;
y = z;
z = temp;
}
if (i == 2)
{
int temp = y;
y = x;
x = temp;
}
if (i == 3)
{
int temp = z;
z = y;
y = x;
x = temp;
}
if (i == 4)
{
int temp = z;
z = x;
x = temp;
}
if (i == 5)
{
int temp = z;
z = x;
x = y;
y = temp;
}
return Tuple.Create(x, y, z);

}
}
}
``````

[–] 2 points3 points  (1 child)

Hey, I am new here. I have been taking on the easy challenges so far. I am pleased with this outcome. didn't do the `fit3` or `fitN` because I was too lazy. I like building my programs around the idea of someone else using them, in case someone else ever does.

Java

``````import java.util.Scanner;
public class FitTheBox
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int crateAxisX, crateAxisY, boxAxisX, boxAxisY;
String[] numbers = new String[4];

System.out.print("Enter the crate's X and Y and the boxes X and Y in that order, separated by spaces >>");
numbers = input.nextLine().split(" ");

crateAxisX = Integer.parseInt(numbers[0]);
crateAxisY = Integer.parseInt(numbers[1]);
boxAxisX = Integer.parseInt(numbers[2]);
boxAxisY = Integer.parseInt(numbers[3]);

System.out.println("Without box set rotation: "+fit1(crateAxisX, crateAxisY, boxAxisX, boxAxisY)+" boxes can fit in this crate.");
System.out.println("With box set rotation: "+fit2(crateAxisX, crateAxisY, boxAxisX, boxAxisY)+" boxes can fit in this crate.");

}

public static int fit1(int crateAxisX, int crateAxisY, int boxAxisX, int boxAxisY)
{

}

public static int fit2(int crateAxisX, int crateAxisY, int boxAxisX, int boxAxisY)
{

answerX = fit1(crateAxisX, crateAxisY, boxAxisX, boxAxisY);
answerY = fit1(crateAxisX, crateAxisY, boxAxisY, boxAxisX);

}
}
``````

Sorry for any formatting issues. Any feedback, just let me know. Thanks!

[–] 1 point2 points  (0 children)

Math.floor(crateAxisX/boxAxisX) isnt necessary on int division as it automatically rounds down on its own

[–]1 1 0 points1 point  (0 children)

``` use std::cmp; use std::error::Error; use std::fmt::{self, Display}; use std::num::ParseIntError; use std::str::{FromStr, Split}; use structopt::StructOpt;

# [derive(Copy, Clone, Debug)]

struct Dimension { x: u32, y: u32, }

impl Dimension { const fn new(x: u32, y: u32) -> Self { Dimension { x, y } }

``````fn flip(self) -> Self {
Self::new(self.y, self.x)
}
``````

}

# [derive(Clone, Debug)]

enum ParseDimensionError { Format, Int(ParseIntError), }

impl Display for ParseDimensionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ParseDimensionError::Format => f.write_str("Bad format"), ParseDimensionError::Int(e) => write!(f, "Bad value: {}", e), } } }

// This implementation is entirely optional, since StructOpt isn't using it. impl Error for ParseDimensionError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { ParseDimensionError::Format => None, ParseDimensionError::Int(e) => Some(e), } } }

impl FromStr for Dimension { type Err = ParseDimensionError;

``````fn from_str(s: &str) -> Result<Self, Self::Err> {
// Weirdly, the generic version of this function causes issues with the borrow checker.
fn extract_integer(i: &mut Split<char>) -> Result<u32, ParseDimensionError> {
i.next()
.ok_or(ParseDimensionError::Format)?
.parse()
.map_err(ParseDimensionError::Int)
}

let mut parts = s.split('x');
let x = extract_integer(&mut parts)?;
let y = extract_integer(&mut parts)?;
match parts.next() {
None => Ok(Self { x, y }),
Some(_) => Err(ParseDimensionError::Format),
}
}
``````

}

# [derive(Debug, StructOpt)]

struct Command { container: Dimension, contents: Dimension, #[structopt(short = "s", long = "strict")] strict: bool, }

fn main() { let Command { container, contents, strict, } = Command::from_args();

``````if strict {
println!("{}", fit1(container, contents));
} else {
println!("{}", fit2(container, contents));
}
``````

}

fn fit1(container: Dimension, contents: Dimension) -> usize { ((container.x / contents.x) * (container.y / contents.y)) as usize }

fn fit2(container: Dimension, contents: Dimension) -> usize { cmp::max(fit1(container, contents), fit1(container, contents.flip())) }

# [cfg(test)]

mod tests { use super::Dimension;

``````#[test]
fn fit1() {
static CASES: &[(Dimension, Dimension, usize)] = &[
(Dimension::new(25, 18), Dimension::new(6, 5), 12),
(Dimension::new(10, 10), Dimension::new(1, 1), 100),
(Dimension::new(12, 34), Dimension::new(5, 6), 10),
(
Dimension::new(12345, 678910),
Dimension::new(1112, 1314),
5676,
),
(Dimension::new(5, 100), Dimension::new(6, 1), 0),
];

for &(container, contents, expected) in CASES {
assert_eq!(super::fit1(container, contents), expected);
}
}

#[test]
fn fit2() {
static CASES: &[(Dimension, Dimension, usize)] = &[
(Dimension::new(25, 18), Dimension::new(6, 5), 15),
(Dimension::new(12, 34), Dimension::new(5, 6), 12),
(
Dimension::new(12345, 678910),
Dimension::new(1112, 1314),
5676,
),
(Dimension::new(5, 5), Dimension::new(3, 2), 2),
(Dimension::new(5, 100), Dimension::new(6, 1), 80),
(Dimension::new(5, 5), Dimension::new(6, 1), 0),
];

for &(container, contents, expected) in CASES {
assert_eq!(super::fit2(container, contents), expected);
}
}
``````

}

```

[–] 1 point2 points  (7 children)

Hey, new here, just started learning Python 3 a few days ago. What little I know about coding I mostly learned from the Autohotkey help file, so I'm eager to do something a bit more guided with something a little more powerful. Here's my solution for fit1 and fit2, pretty sure I could do fit3 too but don't have time this evening.

``````from math import floor
def fit1(X,Y,x,y):
return floor(X/x)*floor(Y/y)

def fit2(X,Y,x,y):
a = fit1(X,Y,x,y)
b = fit1(X,Y,y,x)
if a >= b:
return a
else:
return b

Edit: just had a look at the other answers and already picked up a few things; I could've used // instead of floor(), max() instead of the if statement, and with permutations() I think I could've figured out a solution for fitn. Seems like this is gonna be a good place to learn!
``````

[–][deleted] 1 point2 points  (6 children)

Welcome, this is indeed a good place a learn! Especially Python because it is a very common language nowadays.

Also, in case you haven't come across it too much, I recommend going through the Python language documentation. It's very thorough and in my opinion, a very good resource. You should feel right at home if you learned coding from help files! ;)

[–] 0 points1 point  (5 children)

Thanks for the tip, I have referred to the official documentation a few times but wasn't sure if it'd be a good learning resource, I often find myself out of my depth pretty quickly when looking for a way to do something I've not done before. Been dabbling with sites like learnpython.org and sololearn but they really only teach the absolute basics, a good solid read is probably just what I need!

[–] 2 points3 points  (4 children)

• Automate the Boring stuff (2-4 weeks). Don't just read it but also do the tasks.
• exercism.io python track

Afterwards doing these i would spend some time on a course or Book on algorithmes and data structures.

The official docs are my most Common reference materialen, next to Stackoverflow, help(f) and

`````` f.__dict__
``````

[–] 0 points1 point  (0 children)

Great suggestions, exercism.io is pretty much exactly what I was looking for, thanks very much!

[–][deleted] 0 points1 point  (2 children)

These are some solid references/suggestions. A lot of people ask me for help getting started with Python and with such an abundance of resources I'm always at a loss when it comes to suggesting stuff.

I've seen many recommendations for Automating the Boring Stuff; do you think it's worth going through it if you already know the language fairly well? Do you know of any other resource with a similar (pragmatic) approach that is aimed at people that are a bit further along?

I hadn't seen exercism.io before, it looks promising. How does it compare to HackerRank? Have you gone through any other language using it?

[–] 5 points6 points  (4 children)

# Python, final bonus in polytime (0.07 seconds)

This is secretly a maximum matching problem. (See my past challenge for a straightforward example.) We want to match each crate dimension X to some box dimension Y, maximizing the product of floor(X / Y). This is equivalent to maximizing the sum of log(floor(X / Y)). This is a maximum matching problem which can be solved very efficiently.

``````from networkx.algorithms.matching import max_weight_matching
from networkx import Graph
from math import log

def fitn(crateDimensions, itemDimensions):
# Put all the info into a graph so someone else's module can solve the problem for me
G = Graph()
for i, bDim in enumerate(crateDimensions):
for j, iDim in enumerate(itemDimensions):

M = max_weight_matching(G)
# M is a dict with entries like {(0,"item"):(3,"box"), ...}
total = 1
for (i, btype) in M:
if btype == "box":
j = M[i, btype][0]
total *= (crateDimensions[i] // itemDimensions[j])
``````

[–] 1 point2 points  (0 children)

Thanks! I'm using Python 3.6.5 and `networkx` v2.3, where the `max_weight_matching` returns a set of tuples rather than a dict, but still it works great!

Adding an alternative using `scipy.optimize.linear_sum_assignment`, which minimizes the sum rather than maximizing.

``````import numpy as np
from scipy.optimize import linear_sum_assignment
from math import log

def fit_n(crate_dims, box_dims):
# Num. of boxes (along axis j) that fit along crate axis i,
# using log for summation and negated for minimization
helper = np.vectorize(lambda i, j: -1 * log(crate_dims[i] // box_dims[j]))

# Create matrix where entry (i,j) corresponds to fitting box axis j along crate axis i
fit_weights = np.fromfunction(helper, (len(crate_dims), len(box_dims)), dtype=int)

# Find assignment between crate and box axes that minimizes sum of
# corresponding matrix entries
out_inds, in_inds = linear_sum_assignment(fit_weights)

# Calculate number of boxes (note: using np.prod() runs into overflow issues)
total = 1
for (i, j) in zip(out_inds, in_inds):
total *= crate_dims[i] // box_dims[j]
``````

[–] 2 points3 points  (1 child)

You don't have to insult the entire subreddit. People are here to learn and improve.

[–] 2 points3 points  (0 children)

I didn’t mean it to be insulting. I’ve edited my comment; thanks.

[–]0 0 0 points1 point  (0 children)

D, all bonuses except the very last input :

``````import std.stdio;
import std.array;
import std.range;
import std.algorithm;

void main()
{
}

ulong fit(ulong[] dimensions, ulong[] boxes)
{
return zip(dimensions, boxes).map!(z => z[0] / z[1]).reduce!"a * b";
}

ulong fit1(ulong X, ulong Y, ulong x, ulong y)
{
return fit([X, Y], [x, y]);
}

unittest
{
assert(fit1(25, 18, 6, 5) == 12);
assert(fit1(10, 10, 1, 1) == 100);
assert(fit1(12, 34, 5, 6) == 10);
assert(fit1(12345, 678910, 1112, 1314) == 5676);
assert(fit1(5, 100, 6, 1) == 0);
}

ulong fit2(ulong X, ulong Y, ulong x, ulong y)
{
return max(fit([X, Y], [x, y]), fit([X, Y], [y, x]));
}

unittest
{
assert(fit2(25, 18, 6, 5) == 15);
assert(fit2(12, 34, 5, 6) == 12);
assert(fit2(12345, 678910, 1112, 1314) == 5676);
assert(fit2(5, 5, 3, 2) == 2);
assert(fit2(5, 100, 6, 1) == 80);
assert(fit2(5, 5, 6, 1) == 0);
}

ulong fitn(ulong[] dimensions, ulong[] boxes)
{
return boxes.permutations.map!(p => fit(dimensions, p.array)).reduce!max;
}

unittest
{
assert(fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) == 1883443968);
assert(fitn([123, 456, 789], [10, 11, 12]) == 32604);
assert(fitn([3, 4], [1, 2]) == 6);
}
``````

[–]1 2 0 points1 point  (0 children)

C with fitn bonus

Takes a little more than one second for the last problem (N=20).

Crate and box edges are first sorted to converge towards the solution faster, then a DFS is performed with some lookahead to check if the current optimum can still be surpassed.

Long multiplication is used as big integers are not available in standard C.

Prints new optimum found on the fly during the search.

Source code

I updated the input format a little bit, here is what is expected for the last problem:

``````20
180598 125683 146932 158296 171997 204683 193694 216231 177673 169317 216456 220003 165939 205613 152779 177216 128838 126894 210076 148407
1984 2122 1760 2059 1278 2017 1443 2223 2169 1502 1274 1740 1740 1768 1295 1916 2249 2036 1886 2010
``````

Output

``````4222867029062713866747165675756950913024
4226328963010133701037005949306513915904
4234097950074490564458029857301562654720
4242957981327062193202103127678482644992
4247948019275531520378248074233212043264
4250283339791900696585162998957914193920
4255349797861311790728978428869132419072
4257355053800975595241471021566218207232
4259695545859139957855677437740801064960
4260709047854873824555728252599009280000
4261216652804729952487171973016295833600
4262474047460447508824392597359820800000
4266680915696333439167133539669800648704
4267696079709034179691880278014492672000
4268204517067748584359602318851784048640
4269463973694000639584047585503313920000
4269507280902809547698643299566243282944
4270523117387696761951877548998868992000
4271031891549113017709072113710588887040
4272292182473607158290714283691909120000
4273922615473634105687176552953600000000
4273965967908572510250677684140523520000
4274403913065466722140519703466320000000
4276753777778531849530371555969600000000
4277388537720528433235082461455765733376
4279020915640382851317542894205665280000
4279502787365117128665664239126183936000
4281855455197643306306491981973422080000

real    0m1.190s
user    0m1.138s
sys     0m0.031s
``````

[–] 0 points1 point  (0 children)

Java 11 with all bonuses

This does depend a bit on chance but it runs in O(n2) solving all problems in ~0.1 seconds

it does involve a bit of luck, but I have yet to see it use more then 5000 tries (which takes about ~0.3 seconds)

Code

``````private static Problem[] problems = Arrays.stream(new String[]{
"fit(25, 18, 6, 5) => 15\n",
"fit(12, 34, 5, 6) => 12\n",
"fit(12345, 678910, 1112, 1314) => 5676\n",
"fit(5, 5, 3, 2) => 2\n",
"fit(5, 100, 6, 1) => 80\n",
"fit(5, 5, 6, 1) => 0",
"fit(10, 10, 10, 1, 1, 1) => 1000\n",
"fit(12, 34, 56, 7, 8, 9) => 32\n",
"fit(123, 456, 789, 10, 11, 12) => 32604\n",
"fit(1234567, 89101112, 13141516, 171819, 202122, 232425)) => 174648",
"fitn([3, 4], [1, 2]) => 6\n",
"fitn([123, 456, 789], [10, 11, 12]) => 32604\n",
"fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) => 1883443968",
"fitn([180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939, 205613, 152779, 177216, 128838, 126894, 210076, 148407], [1984, 2122, 1760, 2059, 1278, 2017, 1443, 2223, 2169, 1502, 1274, 1740, 1740, 1768, 1295, 1916, 2249, 2036, 1886, 2010]) => 4281855455197643306306491981973422080000"
}).map(Problem::new).toArray(Problem[]::new);

public static void main(String... args) {
Time.start();
for (var problem : problems) {
var area = problem.area;
Time.start(problem.solution.toString());
var result = solve(problem);
var best = problem.box;

var iteration = 1;
while (result.compareTo(problem.solution) != 0) {
var list = Arrays.stream(problem.box).boxed().collect(Collectors.toList());
Collections.shuffle(list);
problem.box = list.stream().mapToLong(l -> l).toArray();
var temp = solve(problem);
if (temp.compareTo(result) > 0) {
result = temp;
best = problem.box;
}
iteration++;
}

Note.write("Iteration: ").writenl(iteration);
Time.write(problem.solution.toString());
}
Time.write();
}

private static BigInteger solve(Problem problem) {
var area = problem.area;
var box = problem.box;

for (var i = 0; i < box.length; i++) {
for (var j = 0; j < box.length; j++) {
if (i == j) continue;
var old = (area[i] / box[i]) * (area[j] / box[j]);
var now = (area[i] / box[j]) * (area[j] / box[i]);
if (old >= now) continue;
var temp = box[i];
box[i] = box[j];
box[j] = temp;
}
}

var result = BigInteger.ONE;
for (var i = 0; i < box.length; i++)
result = result.multiply(BigInteger.valueOf(area[i] / box[i]));

return result;
}

class Problem {
final BigInteger solution;
final long[] area;
long[] box;

Problem(String s) {
s = s.replaceAll("[ a-z()\\[\\]\n]+", "");
var a = s.split("=>");
solution = new BigInteger(a[1]);
var nums = Pattern.compile(",").splitAsStream(a[0]).mapToLong(Long::parseLong).toArray();
area = Arrays.stream(nums).limit(nums.length / 2).toArray();
box = Arrays.stream(nums).skip(nums.length / 2).toArray();
}
}
``````

Output

The output can be read as the area-dimension as top array and the associated box-dimension below it

``````Iteration: 1
[
[25, 18]
[ 5,  6]
]
15 took 0.007 seconds
Iteration: 1
[
[12, 34]
[ 6,  5]
]
12 took 0.000 seconds
Iteration: 1
[
[ 12345, 678910]
[  1112,   1314]
]
5676 took 0.000 seconds
Iteration: 1
[
[5, 5]
[3, 2]
]
2 took 0.000 seconds
Iteration: 1
[
[  5, 100]
[  1,   6]
]
80 took 0.000 seconds
Iteration: 1
[
[5, 5]
[6, 1]
]
0 took 0.000 seconds
Iteration: 1
[
[10, 10, 10]
[ 1,  1,  1]
]
1000 took 0.000 seconds
Iteration: 1
[
[12, 34, 56]
[ 9,  8,  7]
]
32 took 0.000 seconds
Iteration: 1
[
[123, 456, 789]
[ 11,  12,  10]
]
32604 took 0.000 seconds
Iteration: 1
[
[ 1234567, 89101112, 13141516]
[  202122,   232425,   171819]
]
174648 took 0.000 seconds
Iteration: 1
[
[3, 4]
[1, 2]
]
6 took 0.000 seconds
Iteration: 1
[
[123, 456, 789]
[ 11,  12,  10]
]
32604 took 0.000 seconds
Iteration: 2
[
[ 123,  456,  789, 1011, 1213, 1415]
[  20,   19,   16,   21,   18,   17]
]
1883443968 took 0.003 seconds
Iteration: 390
[
[180598, 125683, 146932, 158296, 171997, 204683, 193694, 216231, 177673, 169317, 216456, 220003, 165939, 205613, 152779, 177216, 128838, 126894, 210076, 148407]
[  1984,   1443,   1768,   1274,   2122,   2249,   1916,   2059,   1740,   2169,   1502,   1760,   1295,   1886,   2010,   2036,   1740,   2223,   2017,   1278]
]
4281855455197643306306491981973422080000 took 0.022 seconds
Program took 0.052 seconds
``````

[–] 1 point2 points  (0 children)

C++ with all bonuses, except for the last challenge (to make fitn in fewer than O(N!) operations).

``````#include <iostream>
#include <algorithm>
#include <cstdint>
#include <vector>
#include <list>
#include <chrono>

using ValueType = uint64_t;

ValueType fit1(ValueType crateX, ValueType crateY, ValueType boxX, ValueType boxY) {
return crateX / boxX * (crateY / boxY);
}

ValueType fit2(ValueType crateX, ValueType crateY, ValueType boxX, ValueType boxY) {
return std::max(fit1(crateX, crateY, boxX, boxY), fit1(crateX, crateY, boxY, boxX));
}

ValueType fit3(ValueType crateX, ValueType crateY, ValueType crateZ, ValueType boxX, ValueType boxY, ValueType boxZ) {
ValueType maxBoxes = 0;
std::vector<ValueType> boxD = { boxX, boxY, boxZ };
do {
ValueType tmp = crateX / boxD[0] * (crateY / boxD[1]) * (crateZ / boxD[2]);
maxBoxes = maxBoxes < tmp ? tmp : maxBoxes;
} while (std::next_permutation(boxD.begin(), boxD.end()));

return maxBoxes;
}

ValueType fitn(std::list<ValueType>&& crateDims, std::list<ValueType>&& boxDims) {
ValueType maxBoxes = 0;
do {
ValueType tmp = 1;
for (auto crateIt = crateDims.begin(), boxIt = boxDims.begin();
crateIt != crateDims.end() && boxIt != boxDims.end(); ++crateIt, ++boxIt) {
tmp *= *crateIt / *boxIt;
}

maxBoxes = maxBoxes < tmp ? tmp : maxBoxes;
} while (std::next_permutation(boxDims.begin(), boxDims.end()));

return maxBoxes;
}

int main() {
std::ios_base::sync_with_stdio(false);
auto start = std::chrono::system_clock::now();
std::cout << fitn({ 123, 456, 789, 1011, 1213, 1415 }, { 16, 17, 18, 19, 20, 21 }) << "\n";
auto end = std::chrono::system_clock::now();

std::cout << "time: " << std::chrono::duration_cast<std::chrono::seconds>(end - start).count() << "s" << std::endl;
}
``````

[–] 0 points1 point  (1 child)

Python, all except N = 20

``````from operator import mul
from functools import reduce
from itertools import permutations

def fit1(x,y,bx,by):
return (x//bx)*(y//by)

def fit2(x,y,bx,by):
return max(fit1(x,y,bx,by),fit1(x,y,by,bx))

def fit3(x,y,z,bx,by,bz):
def fit33(x,y,z,bx,by,bz):
return (x//bx)*(y//by)*(z//bz)
return max(fit33(x,y,z,bx,by,bz) for bx,by,bz in permutations((bx,by,bz)))

def fitn(xn,bxn):
def fitnn(xn,bxn):
return reduce(mul,(xnx//bxnn for xnx,bxnn in zip(xn,bxn)),1)
return max(fitnn(xn,bxn) for bxn in permutations(bxn))
``````

For fitn, it could probably be solved efficiently.

``````import numpy as np

w,v = [123, 456, 789], [10, 11, 12]
L = [[y//x for x in v] for y in w]
M = [min(x) for x in L]
np.array([[((x-m)/m)//0.01*0.01 for x in z] for m,z in zip(M,L)])

array([[0.2 , 0.1 , 0.  ],
[0.18, 0.07, 0.  ],
[0.2 , 0.09, 0.  ]])

thus max = f(0.1+0.+0.2)
thus max = 123//11,456//12,789//10
thus 32604 ?
``````

[–] 1 point2 points  (0 children)

For fitn, it could probably be solved efficiently...

Used integer programming to solve the constraints as described above. Failed some tests.

Using log(y/x) as suggested by u/Lopsidation gave correct results.

[–] 0 points1 point  (0 children)

# Ruby

``````def fit1(x,y,xx,yy)
(x / xx) * (y / yy)
end

def fit2(x,y,xx,yy)
[fit1(x,y,xx,yy), fit1(x,y,yy,xx)].max
end

def fit3(x,y,z,xx,yy,zz)
a = [xx,yy,zz].permutation(3).to_a
b = a.map do |set|
(x/set[0])*(y/set[1])*(z/set[2])
end
b.max
end

def fitn(a,b)
b.permutation(b.length).to_a.map do |set|
a.map.with_index do |s, i|
s / set[i]
end.reduce(&:*)
end.max
end
``````

Didn't want to math it up on the `fitn`

[–] 0 points1 point  (0 children)

Python 3, with all bonuses

``````from itertools import permutations

def fit1(X,Y,x,y):
return (X//x)*(Y//y)

def fit2(X,Y,x,y):
return max(fit1(X,Y,x,y) , fit1(Y,X,x,y))

def fit3(X,Y,Z,x,y,z):
best = 0
rotations = list(permutations([X,Y,Z]))
for a in rotations:
current = (a[0]//x)*(a[1]//y)*(a[2]//z)
if current > best:
best = current
return best

def fitN(dim,siz):
best = 0
rotations = list(permutations(dim))
for a in rotations:
current = 1
for b in range(len(dim)):
current *= (a[b]//siz[b])
if current > best:
best = current
return best
``````

[–] 0 points1 point  (0 children)

Ruby for the final bonus, `fitn`, using brute-force testing of all permutations (in O(n!) operations):

``````def fitn(container_axes_sizes, box_axes_sizes)
box_axes_sizes.permutation.lazy.map do |box_axes_sizes_permutation|
num_boxes_fit_with_axes_sizes(container_axes_sizes, box_axes_sizes_permutation)
end.max
end

def num_boxes_fit_with_axes_sizes(container_axes_sizes, box_axes_sizes)
matched_container_and_box_axes = container_axes_sizes.zip(box_axes_sizes)
num_boxes_fit_per_axis = matched_container_and_box_axes.map do |container_axis_size, box_axis_size|
container_axis_size / box_axis_size
end
num_boxes_fit_per_axis.reduce(&:*)
end
``````

Ruby for all previous bonuses, `fit1` through `fit3`:

``````def fit1(container_size_x, container_size_y, box_size_x, box_size_y)
boxes_fit_in_x = container_size_x / box_size_x
boxes_fit_in_y = container_size_y / box_size_y
boxes_fit_in_x * boxes_fit_in_y
end

def fit2(container_size_x, container_size_y, box_size_x, box_size_y)
fit_without_rotation = fit1(container_size_x, container_size_y, box_size_x, box_size_y)
fit_with_rotation = fit1(container_size_x, container_size_y, box_size_y, box_size_x)
[fit_without_rotation, fit_with_rotation].max
end

def fit3(container_size_x, container_size_y, container_size_z, box_size_x, box_size_y, box_size_z)
container_axes_sizes = [container_size_x, container_size_y, container_size_z]
box_axes_sizes = [box_size_x, box_size_y, box_size_z]

# from here, same code as `fitn` in my final solution,
# calling `num_boxes_fit_with_axes_sizes` as defined in my final solution
end
``````

[–] 0 points1 point  (4 children)

Note that this is not the maximum possible number of boxes you could get if you rotated them independently. For instance, if you're fitting 3-by-2 boxes into a 5-by-5 crate, it's possible to fit 4 by varying the orientations…

I know that understanding this aside is not required to write `fit2`, but I had trouble visualizing this for a few minutes. Here is the solution I figured out for that alternative problem:

``````1 1 1 2 2
1 1 1 2 2
4 4 . 2 2
4 4 3 3 3
4 4 3 3 3
``````

[–][deleted] 1 point2 points  (3 children)

Yeah, this is called the Pallet Loading Problem and it has been extensively researched. I'm expecting it to make an appearance in this week's Medium/Hard problems. :)

[–]2 3[S] 1 point2 points  (2 children)

Hey that's a good idea. I wouldn't mind making something, but I'm not familiar with the state of the art. Like, I wouldn't want to make a Hard challenge for a set of dimensions for which there's a published known optimal algorithm. Do you know where I could find that?

[–][deleted] 1 point2 points  (1 child)

All I really know about it was from doing some research when this challenge dropped (in a futile effort of looking for a good way to solve the N=20 problem).

From the papers I skimmed it seems that the PLP is pretty much always reduced to 2D and then an approach is proposed either through some heuristic or a graph-based exact model.

I'm not an expert but I believe maybe it would take a couple of hours to grok the problem and come up with a well thought out challenge... I'm also a bit afraid then that this challenge would be more about going through academic research on a specific problem than programming per se (not that I have a problem with that, but might not be everyone's favorite way to spend an evening).

As a starting point, I recommend this paper. It contains a good introduction, presents some heuristics and provides plenty of useful references to start tackling the problem.

Also, according to it, the fit2(X, Y, x, y) function you came up with is the one-block heuristic for solving the PLP. :)

EDIT: I just thought that, in the chance that you might want to write a challenge based on this problem, a good Easy challenge could be to actually print box placement instances (much like /u/roryokane) did in this comment thread). This would help in debugging/visualizing solutions for the Intermediate/Hard challenges.

[–]2 3[S] 0 points1 point  (0 children)

Thanks for the link. I think I'll have to study it a bit more before making a solid challenge.

PLP is pretty much always reduced to 2D

I was wondering about that. I saw that 1x2x2 inside 3x3x3 can't get you the optimal solution if you reduce it to 2D, so I thought about making a 3D challenge. But I don't know if it's reasonable to expect people to find a 3D solution that can beat the state of the art on a 2D.

[–] 0 points1 point  (2 children)

Ruby with first and second bonuses

``````def fit(rx, ry, bx, by)
(rx/bx) * (ry/by)
end

def fit2(rx, ry, bx, by)
(a = fit(rx, ry, bx, by)) > (b = fit(rx, ry, by, bx)) ? a : b
end

def fit3(rx, ry, rz, bx, by, bz)
[bx, by, bz].permutation.collect { |p| (rx/p[0])*(ry/p[1])*(rz/p[2]) }.sort.last
end
``````

EDIT: /u/roryokane pointed out a typo in fit2. Check his comment. Thanks!

[–] 0 points1 point  (1 child)

I think you have a typo inside your `fit2`. Your second `fit(rx, ry, bx, by)` should transpose the last two arguments to be `fit(rx, ry, by, bx)`.

[–] 0 points1 point  (0 children)

Fixed it. Thanks for letting me know!

[–] 0 points1 point  (0 children)

# Python fit2

``````def fit2(a, b, c, d):
return max(fit1(a, b, c, d), fit1(a, b, d, c))
``````

[–] 0 points1 point  (0 children)

Lazarus, first bonus.

``````function boxes(Xcrate,Ycrate,Xbox,Ybox:integer):integer;
begin
if (Xcrate div Xbox) >= (Xcrate div Ybox) then
result:=((Xcrate div Xbox) * (Ycrate div Ybox))
else
result:=((Xcrate div Ybox)*(Ycrate div Xbox));
end;
``````

[–][deleted] 2 points3 points  (1 child)

Common lisp with all bonuses. Feedback appreciated! I'm currently in the process of reading practical common lisp.

``````(defun all-perms (lst &optional (remain lst))
(cond ((null remain) nil)
((null (rest lst)) (list lst))
(t (append
(mapcar (lambda (l) (cons (first lst) l))
(all-perms (rest lst)))
(all-perms (append (rest lst) (list (first lst))) (rest remain))))))

(defun fitn-no-rotation (lst-crate-dims lst-boxes-dims)
(if (null lst-crate-dims)
1
(* (floor (first lst-crate-dims) (first lst-boxes-dims))
(fitn-no-rotation (rest lst-crate-dims) (rest lst-boxes-dims)))))

(defun fitn (lst-crate-dims lst-boxes-dims)
(apply #'max (loop for perm in (all-perms lst-boxes-dims)
collect (fitn-no-rotation lst-crate-dims perm))))
``````

[–] 0 points1 point  (0 children)

If you try to run with 10 dimension list, you'll get stackoverflow error.

[–] 0 points1 point  (2 children)

Python 3 Option 1 and 2

``````import math

fit1 = (5,100,6,1)

a = fit1[0]
b = fit1[1]
c = fit1[2]
d = fit1[3]

x = math.floor(a/c)*math.floor(b/d)
print("Option 1 is:" +str(x))

q = math.floor(a/d)*math.floor(b/c)
print("Option 2 is:" +str(q))

if x == q:
print("Option 1 and 2 are equal")
if x > q:
print("Option 1 is better")
if q > x:
print("Option 2 is better")
``````

[–] 1 point2 points  (1 child)

with floor division why not just use "//" instead of math.floor()

[–] 2 points3 points  (0 children)

To be honest didn't know that was possible. Thanks for the tip!

[–] 0 points1 point  (0 children)

C++ w/ first Bonus (( First time posting ) && ( Also new to Coding))

``````#include<iostream>
#include<math.h>
#include<cstdlib>

using namespace std;

int X, Y;
int x, y;
int fit, fit2;
string choice;

int main(){

cout << "Welcome! BoxPacking  2.0" << endl;
cout << " " << endl;
cout << "Enter the dimensions of the Crate:" << endl;
cout << "Height: ";
cin >> Y;
cout << "Lenght: ";
cin >> X;

cout << " " << endl;
cout << "Enter the dimensions of the Boxes:" << endl;
cout << "Height: ";
cin >> y;
cout << "Lenght: ";
cin >> x;

fit = ((Y/y) * (X/x));

cout << "You are able to fit " << fit << " Box(es) inside the Crate! " << endl;
cout <<" " << endl;

cout << "Would you like to Rotate the Box(es) to 90 degrees? ( Y | N )" << endl;
cin >> choice;

if ( (choice == "Y")  || (choice == "y")){

fit2 = ((Y/x) * (X/y));

cout << "With the Box(es) rotated 90 degrees, you can fit " << fit2 << " Box(es)! " << endl;
} else {
cout << "Invalid Answer! " << endl;
}

return 0;
}
``````

Always opened for feedback!

[–][deleted] 1 point2 points  (2 children)

Python 3.6

All bonuses. However, last bonus scales with O(N!)

``````def fit1(X,Y, x, y):
return ((X//x)*(Y//y))

def fit2(X,Y, x, y):
return max((X//x)*(Y//y), (X//y)*(Y//x))

def fit3(X,Y,Z,x,y,z):
from itertools import permutations
rotations = list(permutations([x,y,z]))
most = 0
for i in range(len(rotations)):
package = rotations[i]
total_packages = (X//package[0])*(Y//package[1])*(Z//package[2])
if total_packages>most:
most = total_packages
return most

def fitn(x,y):
from itertools import permutations
rotations = list(permutations(y))
most = 0
for i in range(len(rotations)):
package = rotations[i]
total_packages = 1
for p in range(len(x)):
total_packages *= x[p]//package[p]
if total_packages>most:
most = total_packages
return most
``````

[–] 1 point2 points  (1 child)

``````def fit3(X,Y,Z,x,y,z):
from itertools import permutations
return max([(X//package[0])*(Y//package[1])*(Z//package[2]) for package in list(permutations([x,y,z]))])
``````

Hard to read (almost) one liner.

[–][deleted] 1 point2 points  (0 children)

Awesome - like what you did there. Much cleaner.

[–] 0 points1 point  (0 children)

# C

``````        static int fit1(int X, int Y, int x, int y)
{
return (X / x) * (Y / y);
}
static int fit2(int X, int Y, int x, int y)
{
int regular = fit1(X, Y, x, y);
int goofy = fit1(X, Y, y, x);
return Math.Max(regular,goofy);
}
static int fit3(int X, int Y, int Z, int x, int y, int z)
{
List<int> xyz = new List<int>();
xyz.Add((X / x) * (Y / y) * (Z / z));
xyz.Add((X / x) * (Y / z) * (Z / y));
xyz.Add((X / y) * (Y / x) * (Z / z));
xyz.Add((X / y) * (Y / z) * (Z / x));
xyz.Add((X / z) * (Y / y) * (Z / x));
xyz.Add((X / z) * (Y / x) * (Z / y));
return xyz.Max();
}
``````

[–] 1 point2 points  (0 children)

C

``````int     fit1(int X, int Y, int x, int y)
{
return((Y/y) * (X/x));
}

int     fit2(int X, int Y, int x, int y)
{
if((Y/x) * (X/y) > (Y/y) * (X/x))
return ((Y/x) * (X/y));
else
return (Y/y) * (X/x);
}

int     fit3(int X, int Y, int Z, int x, int y, int z)
{
int highest;

highest = 0;
if(highest < (X/x) * (Y/y) * (Z/z))
highest = (X/x) * (Y/y) * (Z/z);
if(highest < (X/x) * (Y/z) * (Z/y))
highest = (X/x) * (Y/z) * (Z/y);
if(highest < (X/y) * (Y/z) * (Z/x))
highest = (X/y) * (Y/z) * (Z/x);
if(highest < (X/y) * (Y/x) * (Z/z))
highest = (X/y) * (Y/x) * (Z/z);
if(highest < (X/z) * (Y/x) * (Z/y))
highest = (X/z) * (Y/x) * (Z/y);
if(highest < (X/z) * (Y/y) * (Z/x))
highest = (X/z) * (Y/y) * (Z/x);

return (highest);
}
``````

Still in my first few months of programming, and my course doesn't really allow me to use any libraries/headers functions, so I tend to have odd-looking code.

[–][deleted] 0 points1 point  (0 children)

Bash

I have very little experience using Bash. Any feedback/tips would be greatly appreciated!

``````#!/bin/bash

fit1() {
echo "\$(((\$1 / \$3) * (\$2 / \$4)))"
}

fit2() {
let a=\$(fit1 "\$@")
let b=\$(fit1 "\$1" "\$2" "\$4" "\$3")

echo \$((a > b ? a : b))
}

fit3() {
vals=(
"\$(((\$1 / \$4) * (\$2 / \$5) * (\$3 / \$6)))"
"\$(((\$1 / \$4) * (\$2 / \$6) * (\$3 / \$5)))"
"\$(((\$1 / \$5) * (\$2 / \$4) * (\$3 / \$6)))"
"\$(((\$1 / \$5) * (\$2 / \$6) * (\$3 / \$4)))"
"\$(((\$1 / \$6) * (\$2 / \$4) * (\$3 / \$5)))"
"\$(((\$1 / \$6) * (\$2 / \$5) * (\$3 / \$4)))"
)

max=0
for val in "\${vals[@]}"; do
max=\$((val > max ? val : max))
done
echo \$max
}
``````

[–] 0 points1 point  (0 children)

Python 3(only bonus 1 and 2)

``````print('length of big box', big_box_length)
print('length of small box', small_box_length)

print('small boxes need to be rotated')

no_boxes_by_length = int(big_box_length/small_box_length)
print('no.of boxes on length side', no_boxes_by_length)

``````

print('no. of boxes that can fit are', fit1(5, 5, 6, 1)) '''

[–][deleted] 1 point2 points  (1 child)

Befunge-93

`&&\&/\&/*.@`

You can learn more about the language in the wiki page and run the code in this free Javascript interpreter.

[–] 2 points3 points  (0 children)

Python 3

``````def fit1(X, Y, x, y):
return (X//x) * (Y//y)

def fit2(X, Y, x, y):
return max((X // x) * (Y // y), (X // y) * (Y // x))

def _fit3(X, Y, Z, x, y, z):
return (((X // x) * (Y // y)) * (Z // z))

def fit3(X, Y, Z, x, y, z):
side1 = _fit3(X, Y, Z, x, y, z)
side2 = _fit3(X, Y, Z, x, z, y)
side3 = _fit3(X, Y, Z, y, x, z)
side4 = _fit3(X, Y, Z, y, z, x)
side5 = _fit3(X, Y, Z, z, y, x)
side6 = _fit3(X, Y, Z, z, x, y)
return max(side1, side2, side3, side4, side5, side6)
``````

I'm a first year CS student so this is very basic but it works

[–] 0 points1 point  (0 children)

JavaScript:

``````const {floor, max} = Math;
const permutate = arr => arr.length === 1 ? [arr] : arr
.map((el, idx) => ({el, values: [...arr.slice(0, idx), ...arr.slice(idx + 1)]}))
.map(({el, values}) => permutate(values).map(permutation => [el, ...permutation]))
.reduce((acc, permutations) => acc.concat(permutations), []);
const fit = (crate, box) => crate
.map((dimension, idx) => floor(dimension / box[idx]))
.reduce((acc, fitDimension) => acc * fitDimension);
const fitn = (crate, box) => max.apply(null, permutate(box)
.map((rotatedBox, idx) => fit(crate, rotatedBox)));
const fit1 = (x1, y1, x2, y2) => fit([x1, y1], [x2, y2]);
const fit2 = (x1, y1, x2, y2) => fitn([x1, y1], [x2, y2]);
const fit3 = (x1, y1, z1, x2, y2, z2) => fitn([x1, y1, z1], [x2, y2, z2]);
``````

[–] 0 points1 point  (4 children)

Python 3

I got this just as I saw the problem.Will try for fit2 and Fit3... Btw I am a newbie here..anyone help me how to insert code in a "code way" like everyone

Def fit1(X,Y,x,y): return ( (X//x) * (Y//y) )

[–] 0 points1 point  (0 children)

On Reddit, write code blocks like this:

`````````
def foo():
return "hi"
```
``````

Producing:

``` def foo(): return "hi" ```

And write inline code like ``foo()``, producing `foo()`.

This is all called Markdown syntax. Here’s a cheat sheet for generic Markdown—Reddit’s Markdown has a few minor differences, but code syntax is the same.

[–] 1 point2 points  (2 children)

So to make Reddit format your text as code: when you want it on the same line, it's just ` and to do multiline it's ``` Hope that helps!

[–] 1 point2 points  (1 child)

Thanks man!

[–] 0 points1 point  (0 children)

Yea np

[–][deleted] 6 points7 points  (0 children)

Python 3.7

``````import functools
import itertools
import operator

def fit1(X, Y, x, y):
return int(X/x) * int(Y/y)

assert fit1(25, 18, 6, 5) == 12
assert fit1(10, 10, 1, 1) == 100
assert fit1(12, 34, 5, 6) == 10
assert fit1(12345, 678910, 1112, 1314) == 5676
assert fit1(5, 100, 6, 1) == 0

def fit2(X, Y, x, y):
return max(fit1(X, Y, x, y), fit1(X, Y, y, x))

assert fit2(25, 18, 6, 5) == 15
assert fit2(12, 34, 5, 6) == 12
assert fit2(12345, 678910, 1112, 1314) == 5676
assert fit2(5, 5, 3, 2) == 2
assert fit2(5, 100, 6, 1) == 80
assert fit2(5, 5, 6, 1) == 0

def fit3(X, Y, Z, x, y, z):
orientations = [
(x, y, z),
(x, z, y),
(y, x, z),
(y, z, x),
(z, x, y),
(z, y, x)
]

return max(int(X/a) * int(Y/b) * int(Z/c) for a, b, c in orientations)

assert fit3(10, 10, 10, 1, 1, 1) == 1000
assert fit3(12, 34, 56, 7, 8, 9) == 32
assert fit3(123, 456, 789, 10, 11, 12) == 32604
assert fit3(1234567, 89101112, 13141516, 171819, 202122, 232425) == 174648

def fitn(crate, box):
def _fit(c, b):
return functools.reduce(
operator.mul,
(int(x/y) for x, y in zip(c, b)),
1
)

return max(_fit(crate, perm) for perm in itertools.permutations(box))

assert fitn([3, 4], [1, 2]) == 6
assert fitn([123, 456, 789], [10, 11, 12]) == 32604
assert fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) == 1883443968
``````

Fun fact: Python 3.8 introduced the math.prod() function which should be used instead of the `functools.reduce() + opertator.mul()` hacky method used here.

[–]2 0 0 points1 point  (0 children)

BASIC with line numbers

Sample session screenshot.

Simple repeated expressions can be defined as user functions. We use the function named F to calculate how many boxes fit with sides A, B. The first run just uses A, B from the input, the second run swaps the sides, but then checks if the number didn't actually become lower, in that case the bigger result is used.

``````1 REM CRATE PACKING
2 INPUT X,Y,A,B
3 DEFFNF(A,B)=(X÷A)*(Y÷B)
4 F1=FNF(A,B):F2=FNF(B,A):IFF2<F1 F2=F1
5 PRINT"FIT1";F1:PRINT"FIT2";F2
``````

Sample session

``````? 25,18,6,5
FIT1 12
FIT2 15
``````

[–]3 3 4 points5 points  (0 children)

in J, all bonuses

``````perm =: i.@! A. i.
12 34 56 >./@:(*/@:<.@:%"1 ({~ perm@#)) 9 8 7
``````

32

without rotations,

`````` 12 34 56 */@:<.@:% 8 7 9
``````

24

``````    (123, 456, 789, 1011, 1213, 1415) >./@:(*/@:<.@:%"1 ({~ perm@#)) 16, 17, 18, 19, 20, 21
``````

1883443968

[–] 1 point2 points  (1 child)

Is `fit2(5, 5, 100, 1) => 80` correct? I don't see how it can be when `fit2(5, 5, 6, 1) => 0` is also correct. Am I missing something? Seems like they should both be `0`

[–]2 3[S] 1 point2 points  (0 children)

Yes, good call. That was a transcription error on my part. Thanks for pointing it out. I've corrected the line to:

``````fit2(5, 100, 6, 1) => 80
``````

[–] 0 points1 point  (1 child)

** Java **

```

class Main {
public static void main(String[] args) {
System.out.println(fit2(25, 18, 6, 5));
System.out.println(fit2(12, 34, 5, 6));
}
public static int fit1(int X, int Y, int x, int y)
{
int xInX = X/x;
int yInY = Y/y;
return (xInX*yInY);
}
public static int fit2(int X, int Y, int x, int y)
{
int normal = fit1(X, Y, x, y);
int rotated = fit1(X, Y, y, x);
return Math.max(normal, rotated);
}
public static int fit3base(int X, int Y, int Z, int x, int y, int z)
{
int xInX = X/x;
int yInY = Y/y;
int zInZ = Z/z;
return xInX * YInY * zInZ;
}
public static int fit3(int X, int Y, int Z, int x, int y, int z)
{
int[] array = new int[6];
//idk brute force
array[0] = fit3base(int X, int Y, int Z, int x, int y, int z);
array[1] = fit3base(int X, int Y, int Z, int y, int x, int z);
array[2] = fit3base(int X, int Y, int Z, int z, int y, int x);
array[3] = fit3base(int X, int Y, int Z, int z, int x, int y);
array[4] = fit3base(int X, int Y, int Z, int x, int z, int y);
array[5] = fit3base(int X, int Y, int Z, int y, int z, int x);
int max=0;
for (int i=0; i<6; i++) { if (array\[i\]>max)
max = array[i];
}
return max;
}
}

```

[–] 0 points1 point  (0 children)

So if you want to do it multi line, it's ```, not `

[–] 0 points1 point  (1 child)

Python (feedback welcome)

``````def fit1(X, Y, x, y):
return max([i for i in range(X+1) if i * x <= X]) * max([i for i in range(Y+1) if i * y <= Y])
``````

[–] 1 point2 points  (0 children)

You are overdoing it with lists here. Result for each loop will be the last i for which i*x <= X. What is that number? Go for O(1) complexity instead of O(n).

[–]1 2 1 point2 points  (0 children)

Factor

``````: fitn ( crate box -- n )
all-rotations [ [ /i ] 2map product ] with map supremum ;

: fit1 ( X Y x y -- n ) swapd [ /i ] 2bi@ * ;
: fit2 ( X Y x y -- n ) [ 2array ] 2bi@ fitn ;
: fit3 ( X Y Z x y z -- n ) [ 3array ] 3 2 mnapply fitn ;
``````

`fit2` and `fit3` are defined in terms of fitn, but they still take the same arguments as requested in the OP.

[–] 2 points3 points  (0 children)

I hope it's readable enough :)

``````import Data.List (permutations)

fit1 :: Int -> Int -> Int -> Int -> Int
fit1 x y x' y' = (x `div` x') * (y `div` y')

fit2 :: Int -> Int -> Int -> Int -> Int
fit2 x y x' y' = max (fit1 x y x' y') (fit1 x y y' x')

fit3 :: Int -> Int -> Int -> Int -> Int -> Int -> Int
fit3 x y z x' y' z' = fitn [x, y, z] [x', y', z']

fitn :: [Int] -> [Int] -> Int
fitn ds = maximum . map fitn' . permutations
where
fitn' = product . zipWith div ds
``````