Google Interview Question
Front-end Software EngineersCountry: United States
Interview Type: Phone Interview
void printcolorString(std::string str1, std::string colors[])
{
HANDLE hAndle = GetStdHandle(STD_OUTPUT_HANDLE);
int iNdex = 0;
int nlength = str1.length();
int colorIndex = 0;
while (iNdex <= nlength)
{
if(str1[iNdex] == ' ')
SetConsoleTextAttribute(hAndle, 255);
else
SetConsoleTextAttribute(hAndle , colorIndex++);
printf("%c", str1[iNdex]);
iNdex++;
}
}
import Data.Char
type Color = [String]
zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws)
| isSpace c = zipColorWord cs (w : ws)
| otherwise = (c, w) : zipColorWord cs ws
repeatList :: [String] -> [String]
repeatList xs = ret where
ret = xs ++ repeatList xs
ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])
void printcolorString(std::string str1, std::string colors[])
{
HANDLE hAndle = GetStdHandle(STD_OUTPUT_HANDLE);
int iNdex = 0;
int nlength = str1.length();
int colorIndex = 0;
while (iNdex <= nlength)
{
if(str1[iNdex] == ' ')
SetConsoleTextAttribute(hAndle, 255);
else
SetConsoleTextAttribute(hAndle , colorIndex++);
printf("%c", str1[iNdex]);
iNdex++;
}
}
class bcolors:
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
class ColourString(bcolors):
def __init__(self, string):
self.dictionary = {"l": bcolors.RED,
"o": bcolors.BLUE,
"r": bcolors.GREEN,
"e": bcolors.YELLOW,
"m": bcolors.RED,
"END_COLOUR": bcolors.ENDC}
self.string = string
self.coloured_string = ""
self._colour()
def _colour(self):
previous_char = ""
for char in self.string:
if char.isspace():
self.coloured_string += " "
elif previous_char.isspace():
self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
elif char.lower() in self.dictionary.keys():
self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
else:
self.coloured_string += char
previous_char = char
string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)
class bcolors:
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
class ColourString(bcolors):
def __init__(self, string):
self.dictionary = {"l": bcolors.RED,
"o": bcolors.BLUE,
"r": bcolors.GREEN,
"e": bcolors.YELLOW,
"m": bcolors.RED,
"END_COLOUR": bcolors.ENDC}
self.string = string
self.coloured_string = ""
self._colour()
def _colour(self):
previous_char = ""
for char in self.string:
if char.isspace():
self.coloured_string += " "
elif previous_char.isspace():
self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
elif char.lower() in self.dictionary.keys():
self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
else:
self.coloured_string += char
previous_char = char
string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)
class bcolors:
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
class ColourString(bcolors):
def __init__(self, string):
self.dictionary = {"l": bcolors.RED,
"o": bcolors.BLUE,
"r": bcolors.GREEN,
"e": bcolors.YELLOW,
"m": bcolors.RED,
"END_COLOUR": bcolors.ENDC}
self.string = string
self.coloured_string = ""
self._colour()
def _colour(self):
previous_char = ""
for char in self.string:
if char.isspace():
self.coloured_string += " "
elif previous_char.isspace():
self.coloured_string += (bcolors.BLUE+char+self.dictionary["END_COLOUR"])
elif char.lower() in self.dictionary.keys():
self.coloured_string += (self.dictionary[char.lower()]+char+self.dictionary["END_COLOUR"])
else:
self.coloured_string += char
previous_char = char
string = "Lorem ipsum dolor sit amet"
first = ColourString(string)
print(first.coloured_string)
#include <stdio.h>
#include <stdlib.h>
// #define IMRed ......, where ..... you can repace ASCII of your choice of compiler or header file string which give perticular color
#define IMRED .....
#define IMBlue ....
#Define IMGreen ....
#define IMYellow ...
#deinfe IMRESETCOLOR_SPACE ...
void Red(char *ch)
{
printf("\n IMRed (%C)",*ch);
}
void Blue(char *ch)
{
printf("\n IMBlue (%C)",*ch);
}
void Green(char *ch)
{
printf("\n IMGreen (%C)",*ch);
}
void Yellow(char *ch)
{
printf("\n IMYellow (%C)",*ch);
}
void (*func[4])(char *ch);// pointer to function of Red, blue, green ,yellow
int main()
{
char colors[][20]={"red", "blue", "green", "yellow"};
char str[]="Lorem ipsum dolor sit amet";
func[0]=Red;
func[1]=Blue;
func[2]=Green;
func[3]=Yellow;
int color_choice=sizeof(colors)/sizeof(colors[0]); //here 4
char *ch=str;
int color_num=0;
while(*ch!='\0'){
if(*ch==' ')
{
printf("\n IMRESETCOLOR_SPACE ( )");ch++;continue;
}
else
{func[color_num%color_choice](ch);
color_num++;
ch++;
}
}
return 0;
}
private void printLettersInColors(String sentence, String[] colors) {
if(sentence == null || sentence.length() == 0 || colors == null || colors.length == 0) // validation
return;
int no = colors.length; // length can't be more than Integer.MAX_VALUE
int index = 0;
for(char c : sentence.toCharArray()) {
if(c != ' ') {
System.out.println(c+ " - " + colors[index++%no]);
} else {
System.out.println(" ");
}
}
}
Using zip function and infinite repeat of list, it's just couple of lines in Haskell.
import Data.Char
type Color = [String]
zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws)
| isSpace c = zipColorWord cs (w : ws)
| otherwise = (c, w) : zipColorWord cs ws
repeatList :: [String] -> [String]
repeatList xs = ret where
ret = xs ++ repeatList xs
ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])
*Main> ans
[('L',"red"),('o',"blue"),('r',"green"),('e',"yellow"),('m',"red"),('i',"blue"),('p',"green"),('s',"yellow"),('u',"red"),('m',"blue"),('d',"green"),('o',"yellow"),('l',"red"),('o',"blue"),('r',"green"),('s',"yellow"),('i',"red"),('t',"blue"),('a',"green"),('m',"yellow"),('e',"red"),('t',"blue")]
Using zip function, and infinite repeating list, it's just couple of lines in Haskell.
import Data.Char
type Color = [String]
zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws)
| isSpace c = zipColorWord cs (w : ws)
| otherwise = (c, w) : zipColorWord cs ws
repeatList :: [String] -> [String]
repeatList xs = ret where
ret = xs ++ repeatList xs
ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])
import Data.Char
type Color = [String]
zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws)
| isSpace c = zipColorWord cs (w : ws)
| otherwise = (c, w) : zipColorWord cs ws
repeatList :: [String] -> [String]
repeatList xs = ret where
ret = xs ++ repeatList xs
ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])
import Data.Char
type Color = [String]
zipColorWord :: String -> Color -> [(Char, String)]
zipColorWord [] _ = []
zipColorWord (c : cs) (w : ws)
| isSpace c = zipColorWord cs (w : ws)
| otherwise = (c, w) : zipColorWord cs ws
repeatList :: [String] -> [String]
repeatList xs = ret where
ret = xs ++ repeatList xs
ans :: [(Char, String)]
ans = zipColorWord "Lorem ipsum dolor sit amet" (repeatList ["red", "blue", "green", "yellow"])
Javascript solution
function displayColorfulText(colors, text){
const strArray = text.split(' ');
const createSpanElementWithColor = (text, color) => {
let elm = document.createElement('span');
// set the innner text and then add color to it
elm.innerText = text+ ' ';
elm.style.color = color;
console.log(elm);
return elm;
}
// get element by id and then set the inner html to it
let parent = document.createElement('result');
strArray
.map((str, i) => createSpanElementWithColor(str, colors[i]))
.forEach(el => parent.appendChild(el));
document.body.appendChild(parent);
}
displayColorfulText(["red", "blue", "green", "yellow"], "Lorem ipsum dolor sit amet");
C# solution
const ConsoleColor defaultConsoleColor = ConsoleColor.White;
public static void TestPrintColors()
{
// Question
// https://www.careercup.com/question?id=5739126414901248
string[] colors = new string[] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColor(colors, str);
}
static void PrintColor(string[] colors, string str)
{
int colorIndex = 0;
foreach(char log in str)
{
if (char.IsWhiteSpace(log))
{
Console.Write(log);
continue;
}
colorIndex = (colorIndex + 1) % colors.Length;
Console.ForegroundColor = GetColor(colors[colorIndex]);;
Console.Write(log);
}
CleanUpConsole();
}
static ConsoleColor GetColor(string colorStr)
{
ConsoleColor color;
if (!Enum.TryParse(colorStr, true, out color))
{
return defaultConsoleColor;
}
return color;
}
static void CleanUpConsole()
{
Console.WriteLine("");
Console.ForegroundColor = defaultConsoleColor;
}
public static Dictionary<string, ConsoleColor> ColorsMap = new Dictionary<string, ConsoleColor>()
{
{ "red", ConsoleColor.Red },
{ "blue", ConsoleColor.Blue },
{ "green", ConsoleColor.Green },
{ "yellow", ConsoleColor.Yellow },
};
public static void PrintColored(string output, string[] colors)
{
int colorId = 0;
foreach (char c in output)
{
string colorStr = colors[colorId];
if (!ColorsMap.ContainsKey(colorStr))
{
throw new ArgumentException($"Unknown color {colorStr}");
}
PrintColored(c, ColorsMap[colorStr]);
colorId = (colorId + 1) % colors.Length;
}
}
public static void PrintColored(char output, ConsoleColor color)
{
var prevColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.Write(output);
Console.ForegroundColor = prevColor;
}
var colors = ["red","blue" , "green" , "tellow"];
var string = "Lorem ipsum dolor sit amet";
var finalStr = "";
var i = 0;
while(i < string.length) {
var char = string[i];
if(char !== " ") {
var current = colors.shift();
finalStr += `<span style="font-size:20px;color:${current}">${char} </span>`;
colors.push(current);
}
i++;
}
console.log(finalStr);
var colors = ["red","blue" , "green" , "tellow"];
var string = "Lorem ipsum dolor sit amet";
var finalStr = "";
var i = 0;
while(i < string.length) {
var char = string[i];
if(char !== " ") {
var current = colors.shift();
finalStr += `<span style="font-size:20px;color:${current}">${char} </span>`;
colors.push(current);
}
i++;
}
console.log(finalStr);
JavaScript Solution
const colorPrinter = (str, colorsArray) => {
let i = 0;
str.split('').forEach((ch, ind) => {
if(ch !== ' '){
i = (i === colorsArray.length) ? 0 : i;
console.log(`Character ${ch} : ${colorsArray[i]}`);
i++;
}
});
}
colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);
JavaScript Solution:
const colorPrinter = (str, colorsArray) => {
let i = 0;
str.split('').forEach((ch, ind) => {
if(ch !== ' '){
i = (i === colorsArray.length) ? 0 : i;
console.log(`Character ${ch} : ${colorsArray[i]}`);
i++;
}
});
}
colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);
const colorPrinter = (str, colorsArray) => {
let i = 0;
str.split('').forEach((ch, ind) => {
if(ch !== ' '){
i = (i === colorsArray.length) ? 0 : i;
console.log(`Character ${ch} : ${colorsArray[i]}`);
i++;
}
});
}
colorPrinter('Lorem ipsum in the world', ['red', 'blue', 'green', 'yellow', 'white']);
document.write(colorLetters("Lorem ipsum dolor sit amet",["red", "blue", "green", "yellow"]));
function colorLetters(sentence, colors){
let count =0;
let result = '';
for (let i=0;i< sentence.length; i++){
if (sentence[i] !== '') {
result += `<span style="color: ${colors[count]}">${sentence[i]}</span>`;
count++;
if (count>colors.length-1){
count =0;
}
}else{
result +=sentence[i];
}
}
return result;
}
const colors = ["red", "blue", "green", "yellow"];
const str= "Lorem ipsum dolor sit amet";
const printStrColors = (str="", colors=[]) => {
let colorIndex = 0;
const strArr = [...str];
const getColor = () => {
const index = colorIndex % colors.length;
colorIndex ++;
return colors[index];
}
const getStyle = letter => {
if(new RegExp(/\w/).test(letter)) {
return `style="color: ${getColor()}"`
}
return ''
}
return strArr.map(l => `<span ${getStyle(l)}>${l}</span>`).join('')
}
printStrColors(str, colors)
const colors = ["red", "blue", "green", "yellow"];
const str= "Lorem ipsum dolor sit amet";
const printStrColors = (str="", colors=[]) => {
let colorIndex = 0;
const strArr = [...str];
const getColor = () => {
const index = colorIndex % colors.length;
colorIndex ++;
return colors[index];
}
const getStyle = letter => {
if(new RegExp(/\w/).test(letter)) {
return `style="color: ${getColor()}"`
}
return ''
}
return strArr.map(l => `<span ${getStyle(l)}>${l}</span>`).join('')
}
printStrColors(str, colors)
const colorize = (str, colors) => {
let colorIndex = 0;
return str.split(" ").map(word => {
return word.split("").map((letter, index) => {
if (colorIndex === colors.length) colorIndex = 0;
return `<span style="color: ${colors[colorIndex++]}">${letter}</span>`;
}).join('');
}).join(' ');
};
function cp(colors, str){
var strn = '';
var colnth= colors.length;
var a=[], clsx=[];
str.split(' ').forEach((word, index)=>{
a.push(word.replace(/./g, x=>'%c'+x));
clsx = clsx.concat(word.split('').map((char, idx)=>`color:${colors[(idx+index)%colnth]}`))
})
console.log.apply(this, [a.join(' '), ...clsx])
}
const colors = ['red','blue','green','yellow'];
const str = 'Lorem ipsum dolor sit amet';
const wrappper = document.getElementById('wrappper')
let emptyItemCount = 0;
const splitedStr = str.split('')
for(let i = 0, len = splitedStr.length; i < len; i++) {
const letter = splitedStr[i]
if (letter === ' ') {
const text = document.createElement('span')
text.innerHTML = ' '
wrappper.appendChild(text)
emptyItemCount++;
continue;
}
const strong = document.createElement('strong')
strong.innerHTML = letter
const colorIndex = (i - emptyItemCount) % 4
strong.style.color = colors[colorIndex]
wrappper.appendChild(strong)
}
const colors = ['red','blue','green','yellow'];
const str = 'Lorem ipsum dolor sit amet';
const wrappper = document.getElementById('wrappper')
let emptyItemCount = 0;
const splitedStr = str.split('')
for(let i = 0, len = splitedStr.length; i < len; i++) {
const letter = splitedStr[i]
if (letter === ' ') {
const text = document.createElement('span')
text.innerHTML = ' '
wrappper.appendChild(text)
emptyItemCount++;
continue;
}
const strong = document.createElement('strong')
strong.innerHTML = letter
const colorIndex = (i - emptyItemCount) % 4
strong.style.color = colors[colorIndex]
wrappper.appendChild(strong)
}
- Popeye May 08, 2019