Generate string of random characters cocoa? - string

I know how to generate random numbers, but what I really need is a string of random characters. This is what I have so far:
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789?%$";
char generated;
generated = //how do i define this?
NSLog(#"generated =%c", generated);
[textField setStringValue:generated];

-(NSString*)generateRandomString:(int)num {
NSMutableString* string = [NSMutableString stringWithCapacity:num];
for (int i = 0; i < num; i++) {
[string appendFormat:#"%C", (unichar)('a' + arc4random_uniform(25))];
}
return string;
}
then Call it like this for a 5 letter string:
NSString* string = [self generateRandomString:5];

See this SO Q & A.
Generate a random alphanumeric string in Cocoa

Related

Setting a random window title in C++

i wanna set my window title to a random string but i cant figure out how.
I tried to use a random string generator but i dont get how to implement it into the window title.
The random string generator i tried.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
You have to use the _T macro to make sure that the string is in the correct format and set your title using the SetConsoleTitle function :
SetConsoleTitle(_T(*YOUR_RANDOM_TITLE_VAR*));

How to find SHA1 hash?

i got interesting task at school. I have to find message which sha-1 hash lasts with my birthday example. if i was born on 4th may 1932 then the hash must end with 040532. Any suggestions how to find it out?
my solution in C#:
//A create Sha1 function:
using System.Security.Cryptography;
public static string GetSHA1Hash(string text)
{
var SHA1 = new SHA1CryptoServiceProvider();
byte[] arrayData;
byte[] arrayResult;
string result = null;
string temp = null;
arrayData = Encoding.ASCII.GetBytes(text);
arrayResult = SHA1.ComputeHash(arrayData);
for (int i = 0; i < arrayResult.Length; i++)
{
temp = Convert.ToString(arrayResult[i], 16);
if (temp.Length == 1)
temp = "0" + temp;
result += temp;
}
return result;
}
Source
Then a Random String generator:
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
Source
and now you can bruteforce for your combination:
string search = "32";
string result = String.Empty;
int slen = 5;
string myTry = RandomString(slen);
while (!result.EndsWith(search))
{
myTry = RandomString(slen);
result = GetSHA1Hash(myTry);
}
MessageBox.Show(result + " " + myTry);
This would search for a Hash String ending with 32. Happy Bruteforcing :)
EDIT: found one for your example: HXMQVNMRFT gives e5c9fa9f6acff07b89c617c7fd16a9a043040532
Start generating hashes from distinct messages1.
Eventually a hash will be generated with such a property. This is not that bad to brute-force as the range is only 224 (or ~16 million) and SHA is very fast.
There is no shortcut as SHA is a one way cryptographic hash function. In particular here, SHA has the property that "it is infeasible to generate a message that has a given hash".
1 The inputs should be distinct, and a simple counter will suffice. However, it may be more interesting to generate quasi-random messages based on the birthday being sought - e.g. including the date in various forms and sentences Mad Lib style. As long as this doesn't limit the domain, such that there is no qualifying hash, it'll work just as well as any other set of source messages.

Get the value from string vecotr and store in another string?

I am trying to store the string value into vector. And then after storing I want to store in string one by one. In first step split the sting by "," and store into vector. And again try to retrive and get into string.
My code:
CString sAssocVal = "test1, test2, test3";
istringstream ss( sAssocVal.GetBuffer(sAssocVal.GetLength()) );
vector<string> words;
string token;
while( std::getline(ss, token, ',') )
{
words.push_back( token );
}
Try to again retrive from vector:
for(int i = 0; i<words.size(); i++)
std::string st= words[i];
But the value of st is getting NULL always.
where I am missing some thing.
AFAIK the problem is the istringstream initialization, a small modification makes your example work:
http://coliru.stacked-crooked.com/a/698818655cbba4e7
You could first convert CString to std::string, there are a lot of topics about that problem
I resolved this is by using this code.
CString st;
for(int i = 0; i<words.size(); i++)
st= words[i].c_str();

how to get partial string seperated by commas?

I have a string:
string mystring="part1, part2, part3, part4, part5";
How can I just return the first 3 elements without splitting them up first?
so like this:
string newstring="part1, part2, part3";
You could get the first three using:
RegEx r = new RegEx(#"(\S+, \S+, \S+), \S+");
I'm sure there is a better way to write the regex, but I think that would do it for basic inputs.
Try to find Index of 3rd Comma, and then get the substring.
Example
void Main()
{
string mystring="part1, part2, part3, part4, part5";
int thirdCommaIndex = IndexOf(mystring, ',', 3);
var substring = mystring.Substring(0,thirdCommaIndex-1);
Console.WriteLine(substring);
}
int IndexOf(string s, char c, int n)
{
int index = 0;
int count = 0;
foreach(char ch in s)
{
index++;
if (ch == c)
count++;
if (count == n )
break;
}
if (count == 0) index = -1;
return index;
}
This will parse the string trying to find the third comma and throwing it and everything after it away.
string mystring = "part1, part2, part3, part4, part5";
UInt16 CommasFound = 0;
UInt16 Location = 0;
for (Location = 0; (CommasFound < 3) &&
(Location < mystring.Count()); Location++)
if (mystring[Location].Equals(','))
CommasFound++;
if (CommasFound == 3)
{
string newstring = mystring.Substring(0, Location-1);
}
else { // Handle the case where there isn't a third item
}

Need a program to reverse the words in a string

I asked this question in a few interviews. I want to know from the Stackoverflow readers as to what should be the answer to this question.
Such a seemingly simple question, but has been interpreted quite a few different ways.
if your definition of a "word" is a series of non-whitespace characters surrounded by a whitespace character, then in 5 second pseudocode you do:
var words = split(inputString, " ")
var reverse = new array
var count = words.count -1
var i = 0
while count != 0
reverse[i] = words[count]
count--
i++
return reverse
If you want to take into consideration also spaces, you can do it like that:
string word = "hello my name is";
string result="";
int k=word.size();
for (int j=word.size()-1; j>=0; j--)
{
while(word[j]!= ' ' && j>=0)
j--;
int end=k;
k=j+1;
int count=0;
if (j>=0)
{
int temp=j;
while (word[temp]==' '){
count++;
temp--;
}
j-=count;
}
else j=j+1;
result+=word.substr(k,end-k);
k-=count;
while(count!=0)
{
result+=' ';
count--;
}
}
It will print out for you "is name my hello"
Taken from something called "Hacking a Google Interview" that was somewhere on my computer ... don't know from where I got it but I remember I saw this exact question inside ... here is the answer:
Reverse the string by swapping the
first character with the last
character, the second with the
second-to-last character, and so on.
Then, go through the string looking
for spaces, so that you find where
each of the words is. Reverse each of
the words you encounter by again
swapping the first character with the
last character, the second character
with the second-to-last character, and
so on.
This came up in LessThanDot Programmer Puzzles
#include<stdio.h>
void reverse_word(char *,int,int);
int main()
{
char s[80],temp;
int l,i,k;
int lower,upper;
printf("Enter the ssentence\n");
gets(s);
l=strlen(s);
printf("%d\n",l);
k=l;
for(i=0;i<l;i++)
{
if(k<=i)
{temp=s[i];
s[i]=s[l-1-i];
s[l-1-i]=temp;}
k--;
}
printf("%s\n",s);
lower=0;
upper=0;
for(i=0;;i++)
{
if(s[i]==' '||s[i]=='\0')
{upper=i-1;
reverse_word(s,lower,upper);
lower=i+1;
}
if(s[i]=='\0')
break;
}
printf("%s",s);
return 0;
}
void reverse_word(char *s,int lower,int upper)
{
char temp;
//int i;
while(upper>lower)
{
temp=s[lower];
s[lower]=s[upper];
s[upper]=temp;
upper=upper-1;
lower=lower+1;
}
}
The following code (C++) will convert a string this is a test to test a is this:
string reverseWords(string str)
{
string result = "";
vector<string> strs;
stringstream S(str);
string s;
while (S>>s)
strs.push_back(s);
reverse(strs.begin(), strs.end());
if (strs.size() > 0)
result = strs[0];
for(int i=1; i<strs.size(); i++)
result += " " + strs[i];
return result;
}
PS: it's actually a google code jam question, more info can be found here.

Resources