Quick actions

cmd+k|ctrl+k

Navigation

Languages

RGB

Snippet info

Language

JavaScript

Visibility

public

Author

harcom

Created

2019-07-05T11:09:21Z

Updated

2019-07-05T11:10:25Z

// Given an array of strictly the characters 'R', 'G', and 'B', 
// segregate the values of the array so that all the Rs come first, 
// the Gs come second, and the Bs come last. You can only swap
// elements of the array.
// For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], 
// it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B']

function* valuesIterable(order){
    for(let i=0; i<order.length; i++){
        yield order[i];
    }
}


function arrangeValues(values){
    console.log("START: ", values);
    let order = ['R','G','B'];
    let current = 0;

    for(let c of valuesIterable(order)){
        let cursor = current + 1;
        while(cursor < values.length){
            if(values[current] === c){
                current++;
                cursor++;
                continue;
            }
            if(values[cursor] === c){
                let temp = values[current];
                values[current] = values[cursor];
                values[cursor] = temp;
                current++;
            }
            cursor++;
        }
    }
    return values;
}


//RUn
console.log('END: ',arrangeValues(['G','R','B','R','G','G','B','R']));
INFO