Min number of dice rotation

32 Views Asked by At

Hello i'm coding codewars challenge and stuck. There's question :

You are given an array of 6-faced dice. Each die is represented by its face up.

Calculate the minimum number of rotations needed to make all faces the same.

1 will require one rotation to have 2, 3, 4 and 5 face up, but would require two rotations to make it the face 6, as 6 is the opposite side of 1.

The opposite side of 2 is 5 and 3 is 4.

I coded tihs:

function rotations(dieArray) {
    let rotations = 0;
    const opposites = [
        [1, 6],
        [2, 5],
        [3, 4],
    ];

    // Checking what value most often appears

    let countersArr = [];
    for (i = 1; i <= 6; i++) {
        let counter = 0;
        for (j = 0; j < dieArray.length; j++) {
            if (dieArray[j] == i) {
                counter++;
            }
        }
        countersArr.push(counter);
    }
    console.log(countersArr);
    let maxVal = countersArr[0];
    let indexMaxVal = 0;
    for (i = 0; i < countersArr.length; i++) {
        if (countersArr[i] > maxVal) {
            maxVal = countersArr[i];
            indexMaxVal = i;
        }
    }
    console.log(
        `The number that most often appears is ${
            indexMaxVal + 1
        }, appears ${maxVal} times.`
    );

    // finishVal = max of counterArr

    const finishval = indexMaxVal + 1;

    // Check what opposite array includes finishval

    let indexofFinishVal = 0;
    opposites.map((x, i) => {
        if (x.includes(finishval)) {
            indexofFinishVal = i;
        }
    });
    // 2.Check number of rotations to be finishval
    for (i = 0; i < dieArray.length; i++) {
        if (dieArray[i] == finishval) {
            rotations += 0;
        } else if (opposites[indexofFinishVal].includes(dieArray[i])) {
            rotations += 2;
        } else {
            rotations++;
        }
    }
    console.log(rotations);
    return rotations;
}

I got a problem and i think i know where. I think that i can't just take the first number like finishVal because there may be another choice that need less rotations. My assumption was : Take the value that most appears and there's finishVal. I tested my code and 84 test passed 20 fails. If i understand the problem could you help me what can i do for changing my code to work good.

0

There are 0 best solutions below