Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Google.
- 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.
- Do this in linear time and in-place.
- For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B'].
- '''
- from random import randrange
- def generateRGB(desiredLength):
- result = list()
- for i in range(desiredLength):
- r = randrange(3)
- if r == 0:
- result.append('R')
- elif r == 1:
- result.append('G')
- else:
- result.append('B')
- return result
- def sortRGB(rgb):
- # First, I have to sort "R"s, I will use the bubllesort method
- for i in range(len(rgb)-1):
- for j in range(i+1, len(rgb)):
- if rgb[i] != 'R' and rgb[j] == 'R':
- # SWAP
- rgb[i], rgb[j] = rgb[j], rgb[i]
- break
- # Now, all the "R"s are in the beginning of the list
- # Then, I do the same thing for "G"s
- for i in range(len(rgb)-1):
- if rgb[i] == 'R':
- continue
- # If rgb[i] == 'R', the list is sorted until this spot, so I continue
- for j in range(i+1, len(rgb)):
- if rgb[i] != 'G' and rgb[j] == 'G':
- # SWAP
- rgb[i], rgb[j] = rgb[j], rgb[i]
- break
- return rgb
- def prettyPrintRGB(desiredLength):
- rgb = generateRGB(desiredLength)
- RGB = rgb.copy()
- result = sortRGB(rgb)
- print(str(desiredLength) + " elements: " + str(RGB) + " ----> " + str(result))
- # MAIN FUNCTION
- desiredLengths = list(range(5, 11))
- for desiredLength in desiredLengths:
- prettyPrintRGB(desiredLength)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement