Friday, March 24, 2023

Coding Challenge #31

 // based off of Daily Coding Challenge #36
// sort an array of random characters 'R', 'G', and 'B' into the order R, G, B
// Example: [G,B,R,R,B,R,G] -> [R,R,R,G,G,B,B]
function array_extractStringIndices(ary, str){
    var o = [];
    for(var xint = 0;xint < ary.length;xint++)
        if(ary[xint] == str)
            o.push(ary[xint]);
    return o;
}
function array_appendIndices(ary, indices){
    for(var xint = 0;xint < indices.length;xint++)
        ary.push(indices[xint]);
    return ary;
}
function sort(a){
    var Rs = array_extractStringIndices(a, 'R');
    var Gs = array_extractStringIndices(a, 'G');
    var Bs = array_extractStringIndices(a, 'B');
    var o = [];
    o = array_appendIndices(o, Rs);
    o = array_appendIndices(o, Gs);
    o = array_appendIndices(o, Bs);
    return o;
}
if(sort(['G','B','R','R','B','R','G']).toString() == ['R','R','R','G','G','B','B'].toString())
    console.log('algorithm PASS');
else
    console.log('algorithm FAIL');

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...