d3p2

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.4 kB
5
Indexable
Never
function reassembleArray(req, pos, arr){
    for (let i = arr.length-1; i >= 0; i--){
        if (arr[i][pos] == req){
            arr.splice(i, 1);
        }else{
            "nothing to see here";
        }
    }
}

function mostCommon(arr){
    let one = 0;
    let zero = 0;
    let position = 0;

    for (let i = 0; i < arr.length; i++){
        if (arr[i][position] == "1"){
            one++;
        }else if (arr[i][position] == "0"){
            zero++;
        }
        
        if (i == arr.length-1 && arr.length > 1){
            if (one > zero){
                reassembleArray("0", position, arr);
            }else if (zero > one){
                reassembleArray("1", position, arr);
            }else if (one == zero){
                reassembleArray("0", position, arr);
            }

            if (arr.length == 1){
                console.log("Final value of oxygen generator rating: " + arr);
                return arr;
            }
            
            one = 0; 
            zero = 0;
            i = 0;
            position++;
            continue;
        }
    }
}

function leastCommon(arr){
    let one = 0;
    let zero = 0;
    let position = 0;

    for (let i = 0; i < arr.length; i++){
        if (arr[i][position] == "1"){
            one++;
        }else if (arr[i][position] == "0"){
            zero++;
        }
        
        if (i == arr.length-1 && arr.length > 1){
            if (one > zero){
                reassembleArray("1", position, arr);
            }else if (zero > one){
                reassembleArray("0", position, arr);
            }else if (one == zero){
                reassembleArray("1", position, arr);
            }

            if (arr.length == 1){
                console.log("Final value of co2 scrubber rating: " + arr);
                return arr;
            }
            
            one = 0; 
            zero = 0;
            i = 0;
            position++;
            continue;
        }
    }
}

function d3p2(){
    let file = readTextFile("Day3");
    const sFile = file.split("\n");
    const array1 = new Array();
    const array2 = new Array();

    for (let i = 0; i < sFile.length; i++){
        array1.push(sFile[i]);
        array2.push(sFile[i]);
    }

    return binaryToDecimal(mostCommon(array1)) * binaryToDecimal(leastCommon(array2));
}