Algorithm 算法:从字符串创建颜色
我想从给定的字符串创建一种颜色。字符串不必以任何形式与结果颜色相关,但同一字符串应始终产生相同的颜色 这个问题并不局限于特定的编程语言,因此“颜色”应该采用与语言无关的格式,如RGB 如果该算法能够在较宽的色谱中创建颜色,而不仅仅是灰色,那将是一件好事 完全可以是这样的(C++):Algorithm 算法:从字符串创建颜色,algorithm,colors,Algorithm,Colors,我想从给定的字符串创建一种颜色。字符串不必以任何形式与结果颜色相关,但同一字符串应始终产生相同的颜色 这个问题并不局限于特定的编程语言,因此“颜色”应该采用与语言无关的格式,如RGB 如果该算法能够在较宽的色谱中创建颜色,而不仅仅是灰色,那将是一件好事 完全可以是这样的(C++): #包括 int getRedFromString(std::string givenString) {/*您的代码在这里…*/} int getGreenFromString(std::string givenStr
#包括
int getRedFromString(std::string givenString)
{/*您的代码在这里…*/}
int getGreenFromString(std::string givenString)
{/*您的代码在这里…*/}
int getBlueFromString(std::string givenString)
{/*您的代码在这里…*/}
int main()
{
std::string colorString=“FooBar”;
int R=getRedFromString(colorString);
int G=getGreenFromString(colorString);
int B=getBlueFromString(colorString);
}
对字符串进行散列,然后将散列的前三个字节用作红色、蓝色和绿色值。根据您试图实现的目标,有多种方法可以实现这一点。最简单的方法是使用str_stream将字符串转换为流,并将文本值作为无符号字符读取。您可以计算字符串的戈德尔数。基本上是这样
(int)A[0]*256^n+(int)A[1]*256^(n-1)…+(int)A[0]
与我们的数字系统的想法相同,但使用基数256,因为有256个可能的字符值
接下来,只需将要映射到的光谱范围减少一个因子:
e、 假设你想进入范围0。。。2000年
然后取你得到的任何数字除以(你范围内最大的数字)/2000
这种方法的优点是,它将为您提供比RGB更广泛的颜色范围。但是,如果您想要3种原色的简单性,那么您可以用3除,取不同的范围,或者取mod 3。您可以使用任何哈希算法从字符串中创建一个值,该值对于任何给定字符串都是相同的,并从中获取颜色分量 例如,.NET中的
GetHashCode
方法返回一个整数,因此可以很容易地从中创建RGB值:
int RGB = colorString.GetHashCode() & FFFFFFh;
或
我将尝试在字符串上使用MD5:
from hashlib import md5
def get_color_tuple(item)
hash = md5(item).hexdigest()
hash_values = (hash[:8], hash[8:16], hash[16:24]) # note: we ignore the values from 24 to 32, but it shouldn't be a problem.
return tuple(int(value, 16)%256 for value in hash_values)
该算法基本上是这样做的:它获取4个字节(即8个字符)的前三个块,并以256模元组的形式返回它们,因此它们的范围将在[0255]之内
#include <string>
#include <locale>
using namespace std;
int main()
{
locale loc;
string colorString;
COLORREF color;
colorString = "FooBar";
const collate<char>& coll = use_facet<collate<char> >(loc);
color = coll.hash(colorString.data(), colorString.data()+ colorString.length());
}
#包括
使用名称空间std;
int main()
{
地点loc;
字符串颜色字符串;
COLORREF color;
colorString=“FooBar”;
const collate&coll=使用面(loc);
color=coll.hash(colorString.data(),colorString.data()+colorString.length());
}
散列的示例,您的问题是什么?您希望从字符串创建颜色,但尚未指定任何规则。你是希望有人来做这项工作,还是你被困在某个地方,不知道从那里去哪里?那听起来像是家庭作业。“我想从一个给定的字符串创建一种颜色”意味着他是提出这个想法的人,应该知道规则是什么。我目前正在从事一个项目,在这个项目中,可以根据所保存的数据以不同的颜色显示一些GUI元素。我只是想征求关于如何做到这一点的建议。有很多人在回答这个问题,那么你的问题到底是什么呢?这会忽略前三个字节之后的所有内容。前提是你不以任何方式标记它。我的假设是颜色是文本,所以非技术人员可以使用它。所以我假设颜色之间至少有一个间隔。
from hashlib import md5
def get_color_tuple(item)
hash = md5(item).hexdigest()
hash_values = (hash[:8], hash[8:16], hash[16:24]) # note: we ignore the values from 24 to 32, but it shouldn't be a problem.
return tuple(int(value, 16)%256 for value in hash_values)
#include <string>
#include <locale>
using namespace std;
int main()
{
locale loc;
string colorString;
COLORREF color;
colorString = "FooBar";
const collate<char>& coll = use_facet<collate<char> >(loc);
color = coll.hash(colorString.data(), colorString.data()+ colorString.length());
}