Randomly generate from list to set character length

I would like to generate numbers, letters, etc. randomly to a set character length.

I really suck at using repeat, and so far eveything I’ve tried hasn’t worked. So far I got:

generate()
on generate()
	set the_list to {"a", "b", "c"}
	set the list_count to the count of the_list
	set pick to random number from 1 to list_count
	set result to item pick of the_list as string
end generate

to pick randomly from the list.

Basically I want it to repeat until the length of the string is a certain amount of characters long, but I’m not sure how to go about it… repeat with i in x, repeat until count of x is 4, etc. :frowning:

Thanks for the help anyone can offer :slight_smile:

Hi,

As a rule, you shouldn’t use single word variables like “result”. They may be key words.

generate(5)
on generate(n)
set the_list to {“a”, “b”, “c”}
set the list_count to the count the_list
set the_string to “”
repeat n times
set pick to random number from 1 to list_count
set the_result to item pick of the_list as string – result is reserved
set the_string to the_string & the_result
end repeat
return the_string
end generate

gl,

did this using repeat while

set the_list to {"a", "b", "cd", "de", "efg", "fgh", "ghij", "hijk"}
generate(3, the_list)
display dialog result
on generate(repNum, theItems)
	set rep to true
	set theResult to ""
	repeat while rep is true
		set the list_count to the count of theItems
		set pick to random number from 1 to list_count
		set theResult to theResult & item pick of theItems as string
		if (count of theResult) ≥ repNum then
			set theResult to characters 1 through repNum of theResult as string
			return theResult
		end if
	end repeat
end generate

but if all strings in the list have 1 character, you can just do “repeat repNum” (with repNum being a variable representing the no. of characters) and it will repeat 3 times, and the character count of the result will be 3
hope this helps

Here’s a version that uses the ASCII character command to translate a randomly-generated integer into either a digit from 0-9 or a letter from a-z:

set theLength to (text returned of (display dialog "Generate random alphanumeric string of how many characters? (enter an integer, please)" default answer "")) as integer
set n to 0
set outputString to ""
repeat while n < theLength
	set thisNum to (random number from 48 to 122)
	if thisNum < 58 or thisNum > 96 then
		set outputString to outputString & (ASCII character thisNum)
		set n to n + 1
	end if
end repeat
display dialog outputString

wow thanks guys!

Is there any documentation where I can learn to use repeat better?

http://www.applescriptsourcebook.com/tips/AS4AS.html

Well, this is a decent place to start, if you haven’t been there yet…

on generate(len)
	set res to ""
	repeat len times
		set res to res & some item of "abcdefg" -- [your characters here]
	end repeat
	return res
end generate

generate(5)

Totally…sweet.