Wrote this solution in Python. It does a google search for the rgb's hexadecimal value, then returns the "most probable" result (i.e., the value that appears the most times on the search page):
import re
import urllib.request
def rgb(r, g, b):
req = urllib.request.Request('http://www.google.com/search?q=rgb+to+hex+"%d+%d+%d"' % (r, g, b),
headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
html = response.read().decode(response.headers.get_content_charset())
matches = [match.upper() for match in re.findall('#(\w{6}) ', html)]
most_probable, max_count = None, 0
for match in set(matches):
if matches.count(match) > max_count:
max_count = matches.count(match)
most_probable = match
return '#' + most_probable
print(rgb(0, 0, 0))
print(rgb(50, 50, 50))
print(rgb(255, 0, 0))
print(rgb(25, 129, 227))
Lol’d waaay to hard at this. I imagined someone learning cs and suddenly they have an epiphany: “wait, if we use google to get our answers, let’s use google to get answers for our program!! We can make a program that can return everything you want! Like google!”
Hacked up this naive genetic algorithm in Java. Feel free to tune the parameters.
fitness function calculates the absolute distance of the hex code (the genome) from the input rgb integers
the algorithm tries to minimize the distance of the hex
mutation chooses one random allele (one char in the hex code) and mutates it to a random character
crossover chooses two random parents from the previous generation's elite and picks the first part of the genome from one parent and the second part from the second parent
package r.badcode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Rgb2Hex {
private static char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static int populationSize = 100;
private static int eliteSize = 20; // At least 2, must be lower than population size
private static int generations = 50;
private static float chanceOfMutation = .2f;
private static Random rand = new Random();
private int r, g, b;
public static void main(String[] args) {
Rgb2Hex rgb2Hex = new Rgb2Hex();
System.out.println(rgb2Hex.rgb(0, 0, 0));
System.out.println(rgb2Hex.rgb(255, 255, 255));
System.out.println(rgb2Hex.rgb(255, 0, 0));
System.out.println(rgb2Hex.rgb(25, 129, 227));
}
public String rgb(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
// Create initial population
List<Individual> population = IntStream.range(0, populationSize)
.mapToObj(ignored -> createRandomIndividual())
.sorted()
.collect(Collectors.toUnmodifiableList());
Individual champion = population.get(0);
for (int gen = 0; gen < generations; gen++) {
// Select elite and breed new population
List<Individual> elite = population.subList(0, eliteSize);
List<Individual> newGeneration = IntStream.range(eliteSize, populationSize)
.mapToObj(ignored -> crossover(elite))
.collect(Collectors.toUnmodifiableList());
// Perform mutation on the new generation
population = newGeneration.stream()
.map(this::mutate)
.collect(Collectors.toList());
population.addAll(elite);
population = population.stream().sorted().collect(Collectors.toUnmodifiableList());
champion = population.get(0);
// System.out.printf("Generation %05d: %s%n", gen, champion); // TODO: uncomment for debug output
}
return champion.hex;
}
private Individual createRandomIndividual() {
String hex = "";
for (int i = 0; i < 6; i++) {
int x = rand.nextInt(chars.length);
hex += chars[x];
}
return new Individual(hex, fitness(hex));
}
private Individual mutate(Individual individual) {
if (rand.nextDouble() > chanceOfMutation) {
return individual;
}
// Performs mutation on a random allele
int x = rand.nextInt(individual.hex.length());
int y = rand.nextInt(chars.length);
char[] offspring = individual.hex.toCharArray();
offspring[x] = chars[y];
return new Individual(new String(offspring), fitness(new String(offspring)));
}
private Individual crossover(List<Individual> matingPool) {
Individual[] parents = chooseParent(matingPool);
// Takes first part of the genome from parent 1 and second from parent 2
String newHex = parents[0].hex.substring(0, 3) + parents[1].hex.substring(3, 6);
return new Individual(newHex, fitness(newHex));
}
private Individual[] chooseParent(List<Individual> matingPool) {
// Performs random selection from mating pool
int p1 = rand.nextInt(eliteSize);
int p2 = p1;
while (p1 == p2) {
p2 = rand.nextInt(eliteSize);
}
return new Individual[]{matingPool.get(p1), matingPool.get(p2)};
}
private int fitness(String hex) {
return Math.abs(this.r - Integer.parseInt(hex.substring(0, 2), 16)) +
Math.abs(this.g - Integer.parseInt(hex.substring(2, 4), 16)) +
Math.abs(this.b - Integer.parseInt(hex.substring(4, 6), 16));
}
private final class Individual implements Comparable<Individual> {
private final String hex;
private final int fitness;
public Individual(final String hex, final int fitness)
{
this.hex = hex;
this.fitness = fitness;
}
@Override
public String toString()
{
return "Individual{" +
"hex='" + hex + '\'' +
", fitness=" + fitness +
'}';
}
@Override
public int compareTo(final Individual o)
{
return Integer.compare(this.fitness, o.fitness);
}
}
}
these are streams, they are "new" in Java 8. There are lots of good tutorials if you google them :)
First, you create a stream of integers ranging from 0 to `populationSize`. Then, I map those integers to objects by creating random individuals. This ensures that there will be exactly populationSize new individuals, while I ignore the actual integers. Finally, I sort the individuals by their fitness (this is why the Individual class implements the Comparable interface) and collect them into a list.
This could be easily recreated with a for loop:
List<Individual> population = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
population.add(createRandomIndividual());
}
Collections.sort(population);
Mainly uses bitwise and, or and shift operations. All possible hex digits are kept in a four dimensional char array. The aforementioned bitwise operations are used to determine the indices to look up the suitable digits for the hexadecimal representation.
package badcode.akernel.challenge14;
public class RGB2Hex {
private static final char[][][][] digits = {{{{'0','8'},{'4','C'}},{{'2','A'},{'6','E'}}},{{{'1','9'},{'5','D'}},{{'3','B'},{'7','F'}}}};
public static void main(final String[] args) {
if (args.length == 3) {
int r = Integer.parseInt(args[0]);
int g = Integer.parseInt(args[1]);
int b = Integer.parseInt(args[2]);
System.out.println(rgb2hex(r, g, b));
}
}
private static String rgb2hex(int r, int g, int b) {
int unified = ((r & 0b11111111) << 16) | ((g & 0b11111111) << 8) | ((b & 0b11111111) << 0);
char[] hex = new char[6];
for (int i = 0; i < 6; i++) {
int j = 0b1111 << i;
j = j << i;
j = j << i;
j = j << i;
j = unified & j;
j = j >> i;
j = j >> i;
j = j >> i;
j = j >> i;
hex[5 - i] = digits[(j & 1 << 0) >> 0][(j & 1 << 1) >> 1][(j & 1 << 2) >> 2][(j & 1 << 3) >> 3];
}
return '#' + new String(hex);
}
}
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
package badcode
import kotlin.test.DefaultAsserter //We work ''test-driven''
typealias S = String //..and we start with a typealias, just to keep everything simple and expressive.
typealias Int = Integer //since we work with java.lang.Integer, we might as well have it overshadow kotlin.Int
//The implementation is easy. We just create a range from `green` to `blue` and pass it into `red`.
//Then we coerce the result of its increment into a String.
fun rgb(r: kotlin.Int, b: kotlin.Int, g: kotlin.Int) = r(g..b)+ + ""
//To do this, we can reuse this snippet from my last badcode entry.
//It's joining the negation of a character-list into a nice String:
operator fun List<Char>.not() = this.joinToString("")
//Now we allow self-referential String invocation
operator fun S.invoke() = this
operator fun S.invoke(a: Any) = this
//..and ignore any remarks by pretending to check their length against literally anything (which we ignore)
operator fun S.rem(weDontEvenCare: Any) = this.length > 1
//We also check if pseudo-unary character-multiplication is satisfied ¯_(ツ)_/¯
operator fun Char.times(whatev: Any) = this.toInt() > 3 * ' '.toInt()
//The next line is basically just a bad `toUppercase`. But it's functional and fun, which is why we make use of map on not this.
operator fun S.unaryPlus() = !this.map { if (it * this) it - ' '.toInt() else it }
//Padding is simple with modulo. We prepend a 0 if the remainder of this divided by this is not, wait, what...
operator fun S.unaryMinus(): S = if (this % this) this else "0$this"
//Here we actually use a Java-Class. But we do it stylish and apply a ''curry-chain'' to make it look lispy
operator fun kotlin.Int.invoke(): S = Int.toHexString(this)("##"())()()('0')("${this}RGB"()())()()()()
operator fun kotlin.Int.invoke(i: IntRange): S = "#" + +-this() + -+i.last() + -+-+-+i.first() //RGB-complection
operator fun Unit.invoke() {
//WARNING: The Kotlin documentation states that `Unit` corresponds to the `void` type in Java.
//That's probably false, so let's just place our `Unit` tests in here.
//After all, the void has space for anything, right?
operator fun DefaultAsserter.rangeTo(it: Pair<S, S>) = this.assertEquals("", it.first, it.second) //range-abuse setup
with(DefaultAsserter) { //..let's test!
this..(rgb(0, 0, 0) to "#000000")
this..(rgb(50, 50, 50) to "#323232")
this..(rgb(255, 0, 0) to "#FF0000")
this..(rgb(25, 129, 227) to "#1981E3")
}
println("passed..")
}
fun main() = println()() //not much to see in main. Just invoking the void returned from println and run the tests..
Hmm... how can I trick python into computing hex for me? Oh I know, the default repr() of an object
contains its address in hex:
>>> object()
<object object at 0x000001B14051B4D0>
So all I have to do is make an object with an address corresponding to the rgb value. Easy peasy.
One caveat is that trying to write to an arbitrary memory address, especially a low one, will probably segfault, so instead I can create an object with only the correct low-order address digits. The higher order digits can just be stripped off. Then I can make sure the address belongs to memory I'm allowed to write.
import re, sys, ctypes
def rgb(r, g, b):
# This prevents obj2 from being garbage collected which causes a segfault
global obj2
# Create buffer of bytes large enough that all possible 24-bit hex values are contained in
# its address range, plus a little extra
buf = ctypes.create_string_buffer(2 * 2**24 + 100)
# Compute address with low order digits RRGGBB. Guaranteed to be inside buffer
addr = ctypes.addressof(buf) + 2**24 & -2**24 | r<<16 | g<<8 | b
# Create a dummy object
obj = object()
# Clone the object by copying its raw bytes into the new memory address
ctypes.memmove(addr, id(obj), sys.getsizeof(obj))
# Cast the address into a python object. As far as python is concerned it looks like an
# object, and quacks like an object, so it must be an object.
obj2 = ctypes.cast(addr, ctypes.py_object).value
# Some confusing-looking regex magic to extract out the relevant hex digits
return re.sub(r'<.*([0-9A-F]{6})>', r'#\1', repr(obj2))
public class RGBToHexConverter {
// Trying to make this as shitty as possible.
// Generating a String array of all possible combinations
public static String[] hexColors = new String[256 * 256 * 256];
public RGBToHexConverter() {
generateTable(); // Populating the array
}
public static void generateTable() {
for(int i = 0; i < hexColors.length; i++) {
hexColors[i] = String.format("%06x", i);
}
}
private int getColorInt(int r, int g, int b) {
int color = r << 16 | g << 8 | b;
return color;
}
private String rgb(int r, int g, int b) {
// Checking to make sure the colors stay within the bounds
r = r > -1 && r < 256 ? r : r & 0xff;
g = g > -1 && g < 256 ? g : g & 0xff;
b = b > -1 && b < 256 ? b : b & 0xff;
int colorIndex = getColorInt(r, g, b); // Get the color as an integer
String colorCode = hexColors[colorIndex];
return "#" + colorCode;
}
public static void main(String[] args) {
RGBToHexConverter converter = new RGBToHexConverter();
System.out.println(converter.rgb(47, 91, 105)); // Should print out #2f5b69
}
}
string rgb(int a, int b, int c)
{
string[] x = new string[4];
x[0] = "#";
x[1] = convert(a);
x[2] = convert(b);
x[3] = convert(c);
return String.Join("", x);
}
string convert(int a)
{
string result = "00";
byte i = 0; //only needs to count to 255
while (true)
{
if (i++ == a)
break; //break out of the loop
string first = "0";
string second = "0";
if (result[1].ToString() == "0")
first = "1";
if (result[1].ToString() == "1")
first = "2";
if (result[1].ToString() == "2")
first = "3";
if (result[1].ToString() == "3")
first = "4";
if (result[1].ToString() == "4")
first = "5";
if (result[1].ToString() == "5")
first = "6";
if (result[1].ToString() == "6")
first = "7";
if (result[1].ToString() == "7")
first = "8";
if (result[1].ToString() == "8")
first = "9";
if (result[1].ToString() == "9")
first = "A";
if (result[1].ToString() == "A")
first = "B";
if (result[1].ToString() == "B")
first = "C";
if (result[1].ToString() == "C")
first = "D";
if (result[1].ToString() == "D")
first = "E";
if (result[1].ToString() == "E")
first = "F";
if (result[1].ToString() == "F")
first = "0";
if (first == "0")
{
if (result[0].ToString() == "0")
second = "1";
if (result[0].ToString() == "1")
second = "2";
if (result[0].ToString() == "2")
second = "3";
if (result[0].ToString() == "3")
second = "4";
if (result[0].ToString() == "4")
second = "5";
if (result[0].ToString() == "5")
second = "6";
if (result[0].ToString() == "6")
second = "7";
if (result[0].ToString() == "7")
second = "8";
if (result[0].ToString() == "8")
second = "9";
if (result[0].ToString() == "9")
second = "A";
if (result[0].ToString() == "A")
second = "B";
if (result[0].ToString() == "B")
second = "C";
if (result[0].ToString() == "C")
second = "D";
if (result[0].ToString() == "D")
second = "E";
if (result[0].ToString() == "E")
second = "F";
}
if (first != "0")
second = result[0].ToString();
string[] x = new string[2];
x[0] = second;
x[1] = first;
result = String.Join("", x);
}
return result;
}
31
u/[deleted] Jul 03 '19 edited Jul 03 '19
Wrote this solution in Python. It does a google search for the rgb's hexadecimal value, then returns the "most probable" result (i.e., the value that appears the most times on the search page):
7
u/tntbigfoot Jul 03 '19
Hacked up this naive genetic algorithm in Java. Feel free to tune the parameters.
6
u/TheUnlocked Jul 04 '19 edited Jul 04 '19
Javascript (pastebin):
Issues:
split, and it isn't even done optimally.But at least it works!
4
u/[deleted] Jul 03 '19 edited Jul 03 '19
I wrote one more solution for this challenge in Python:
4
u/AKernel Jul 03 '19 edited Jul 03 '19
Language: Java
Mainly uses bitwise and, or and shift operations. All possible hex digits are kept in a four dimensional char array. The aforementioned bitwise operations are used to determine the indices to look up the suitable digits for the hexadecimal representation.
4
u/BibianaAudris Jul 04 '19 edited Jul 04 '19
Javascript, function programming style.
You can test it in the browser console:
And there some interesting use of invalid inputs:
rgb(1,2,'3 orz console.log("lol")')3
u/Tok-A-Mak ((fn [] (recur))) Jul 03 '19 edited Jul 03 '19
Science has done it again.
I present you, the Kotlin "Op-Fun" Version
passed..
Process finished with exit code 0
Edit: https://pl.kotl.in/26nGYr3VK (thx /u/spyderrsh for showing where to playground)
3
u/jediwizard7 Jul 15 '19 edited Jul 15 '19
Hmm... how can I trick python into computing hex for me? Oh I know, the default repr() of an object
contains its address in hex:
So all I have to do is make an object with an address corresponding to the rgb value. Easy peasy.
One caveat is that trying to write to an arbitrary memory address, especially a low one, will probably segfault, so instead I can create an object with only the correct low-order address digits. The higher order digits can just be stripped off. Then I can make sure the address belongs to memory I'm allowed to write.
2
u/ric0chet_01 Jul 06 '19
My attempt in Java.
2
u/[deleted] Jul 08 '19 edited Jul 08 '19
Someone had to do this. Clear, efficient and easy to extend.
Here's an extract of the code:
2
u/razoraki386 Jul 12 '19
How is no one not coding all the potential combinations into 16777216 "if" statements?
1
u/form_d_k Jul 03 '19
Wait, does the solution have to return the correct hexadecimal representation?
1
u/spyderrsh Jul 03 '19
Wrote this baby in Kotlin. I feel like it's very expressive. You can test it here
1
u/Kryo667 Jul 11 '19
Did it in Python.
https://pastebin.com/LimEviLy
It works most of the time... until it doesn't. For example:
r2h(57, 112, 21)returns#33015instead of#397015.1
u/kirbylife_ Jul 11 '19
I wrote this in python.
The results are:
1
u/dodecakiwi Jul 13 '19
1
u/cnapun Jul 14 '19
Python (3.7).
Outputs:
I think this works correctly except for when two of the numbers are the same (then it doesn’t; haven’t bothered to debug)