Untitled

 avatar
user_7066242
plain_text
24 days ago
2.0 kB
9
Indexable
Never
const LENGTH = 9;

let user1 = []
let user2 = []

for (let i = 0; i < LENGTH; i++) {
    user1.push(Math.floor(Math.random()*20))
    user2.push(Math.floor(Math.random()*20))
}

let sets1 = Math.floor(user1.reduce((acc, cur) => (acc + cur), 0) / LENGTH)

let diff1 = user1.map((entry) => entry - sets1)

let sets2 = Math.floor(user2.reduce((acc, cur) => (acc + cur), 0) / LENGTH)

let diff2 = user2.map((entry) => entry - sets2)

console.log(user1, sets1)
console.log(user2, sets2)

console.log(diff1)
console.log(diff2)

let swap1 = [];
let swap2 = [];

for (let i = 0; i < LENGTH; i++) {
    let a = diff1[i]
    let b = diff2[i]

    if (Math.sign(a) === Math.sign(b)) {
        swap1.push([i, 0])
        swap2.push([i, 0])
        continue;
    }

    let diff = Math.min(Math.abs(a), Math.abs(b));

    if (Math.sign(b) === -1) {
        swap1.push([i, diff])
        swap2.push([i, 0])
    } else {
        swap1.push([i, 0])
        swap2.push([i, diff])
    }
}

console.log('SWAP CARDS')
console.log(...swap1)
console.log(...swap2)

swap1.sort((a, b) => b[1] - a[1])
swap2.sort((a, b) => b[1] - a[1])

console.log('SORTED:')
console.log(...swap1)
console.log(...swap2)

let result1 = new Map();
let result2 = new Map()

let p1 = 0;
let p2 = 0;
let start1 = swap1[0][1]
let start2 = swap2[0][1]

while(start1 > 0 && start2 > 0) {
    let cur1 = swap1[p1][1];
    let cur2 = swap2[p2][1];
    
    if (!cur1 || cur1 < start1) {
        p1 = 0;
        start1 = swap1[0][1]
    }

    if (!cur2 || cur2 < start2) {
        p2 = 0;
        start2 = swap2[0][1]
    }

    if (!cur1 || !cur2) {
        continue;
    }

    swap1[p1][1]--
    swap2[p2][1]--

    let res1 = result1.get(swap1[p1][0]) || 0
    result1.set(swap1[p1][0], res1 + 1)

    let res2 = result2.get(swap2[p2][0]) || 0
    result2.set(swap2[p2][0], res2 + 1)
    
    p1++
    p2++
}

console.log('LEFTOVERS:')
console.log(...swap1)
console.log(...swap2)

console.log('TRADE:')
console.log(...result1.entries())
console.log(...result2.entries())
Leave a Comment