Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does this script that makes sure the chosen members of an array are not the same work?

moves = {1; 2; 3; 4}

w = script.Parent

m1 = w.Move1 --These are string values.
m2 = w.Move2
m3 = w.Move3
m4 = w.Move4

function r(n)
	return math.random(n)
end

m1.Value = moves[r(#moves)]

m2.Value = moves[r(#moves)]

	if m2.Value == m1.Value then
		while m2.Value ~= m1.Value do
			m2.Value = moves[r(#moves)]
		end
	end

m3.Value = moves[r(#moves)]

	if m3.Value == m1.Value or
		m3.Value == m2.Value then
			while m3.Value ~= m1.Value and
				m3.Value ~= m2.Value do
					m3.Value = moves[r(#moves)]
				end
			end

m4.Value = moves[r(#moves)]

	if m4.Value == m1.Value or
		m4.Value == m2.Value or
		m4.Value == m3.Value then
			while m4.Value ~= m1.Value and
					m4.Value ~= m2.Value and
					m4.Value ~= m3.Value do
						m4.Value = moves[r(#moves)]
					end
		end

So what this script is supposed to do is to choose a member of the table and make the string values one of them. Now, this works, except for the fact that some of the members chosen are the same.

Any ideas anyone?

Any form of help is greatly appreciated!

Thanks!

P.S.

Before you say anything, no, math.random does not require two numbers. When only one number is given, It will choose a random number from 1 until the number given.

1 comment

0

They are all the same because you have loops ensuring they are all the same

1 answer

✓ Accepted answer

Here is a better way of doing this.

local moves = {1; 2; 3; 4}
local w = script.Parent
local mTable = {

	m1 = w.Move1,
	m2 = w.Move2,
	m3 = w.Move3,
	m4 = w.Move4

}

local function r(n)
    return math.random(n)
end

local function setMoves(m)
	local rand = r(#moves)
	m.Value = moves[rand]
	table.remove(moves,rand) --removes the move from the table so it can't be repeated
end

table.foreach(mTable,function(_,m)
	setMoves(m)
end)

I put the m1,m2... into a table so you can loop through them applying the setMoves function which assigns a random move to them and then removes that move from the table so it won't be repeated again.

If this answers your question, then mark it as the accepted answer.

1 comment

0

Thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.