Related
1 of 10 different cards, randomly distributed, in each box
Any one collecting all 10 cards at the end of the first 21 days will receive 2 weeks paid vacation
every day until Johnny collects all 10 cards.
How many boxes of cereal must Johnny’s mother purchase to collect at least one of each card?
At the end of the program display a sentence indicating whether or not Johnny won the trip. Run the program a few times and compare the results.
it prints out only 01 and 0 for sum of cards dont know why the loop isn't doing the right values.
import java.util.Random;
public class Cereal{
public static void main(String []args) {
String [] wCards = {"eevee","jirachi","pichu","Taillow","flying pikachu","Togekiss","Blastoise","raichu","flareon","lanturn"};
int e=0,j=0,p=0,t=0,fp=0,toge=0,b=0,r=0,f=0,l=0,sum=0,pull;
int[] pokeCards= {e,j,p,t,fp,toge,b,r,f,l};
Random rand = new Random(10);
boolean card = false;
while (card == false) {
pull = rand.nextInt();
if(pull ==0)
e++;
if(pull == 1)
j++;
if(pull== 2)
p++;
if(pull == 3)
t++;
if(pull == 4)
fp++;
if(pull == 5)
toge++;
if(pull == 6)
b++;
if(pull == 7)
r++;
if(pull == 8)
f++;
if(pull== 9)
l++;
for(int i =0; i < pokeCards.length; i++) {
if(pokeCards[i] >= 0) {
card = true;}
sum+= pokeCards[i];
}
System.out.println("Acme Cereal Inc. Disney World Contest Simulation\n");
System.out.println("Total number of boxes of cereal purchased : " + sum);
System.out.println("Card#\tCArd\tNumber of cards collected");
for(int k=0; k < wCards.length;k++) {
System.out.println(k+1 + "\t" + wCards[k] + "\t\t" + pokeCards[k]+1);
}
if(sum<21){
System.out.println("You won a Vacation");
}else {
System.out.println(" sorry no Vacation");
}
}
}
}
I want to make the queue list only show 10 songs at a time, because right now the bot crashes and says that every embed field can only have 1024 characters.
I've put the most important part below, you can find the rest here.
exports.playQueue = (guildId, channel) => {
if (!guilds[guildId] || !guilds[guildId].nowPlaying) {
var embed = new Discord.RichEmbed()
.setColor(9955331)
.setDescription(":mute: Not Playing");
channel.send(embed);
return;
}
var g = guilds[guildId];
var q = "";
var i = 1;
let ytBaseUrl = "https://www.youtube.com/watch?v=";
g.playQueue.forEach((song) => {
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
q += "`" + i++ + "`. ";
q += `[${title}](${ytLink}) | `;
q += "`" + song.length + "`\n";
});
let currSong = g.nowPlaying.title;
if (currSong.length > 30) currSong = currSong.substring(0, 19) + "... ";
var cs = `[${currSong}](${ytBaseUrl+g.nowPlaying.id}) | `;
cs += "`" + g.nowPlaying.length + "`";
var embed = new Discord.RichEmbed()
.setColor(9955331)
.addField(":musical_note: Now Playing", cs);
if (g.loop) embed.setFooter("🔁 Looping playlist");
if (q != "") embed.addField(":notes: Play Queue", q);
channel.send(embed);
}
I would solve the problem by building a queue that goes from the first to the tenth song
// I chose a for loop just because I can break out of it
// This goes on until it reaches the end of the queue or the tenth song, whichever comes first
for (let i = 0; i < g.playQueue.length && i < 9; i++) {
let song = g.playQueue[i];
// This is your part
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
// Instead of directly adding the next line to q, I store it in another variable
let newline = "";
newline += "`" + (i+1) + "`. ";
newline += `[${title}](${ytLink}) | `;
newline += "`" + song.length + "`\n";
// If the sum of the two lengths doesn't exceed the 1024 chars limit, I add them together
// If it is too long, I don't add it and exit the loop
if (q.length + newline.length > 1024) break;
else q += newline;
}
This should fix it, since q should not exceed 1024 characters. This is a simple but effective solution in my opinion.
Feel free to let me know if something doesn't work properly ;)
Prompt the user to enter five numbers, being five people's weights. Store the numbers in an array of doubles. Output the array's numbers on one line, each number followed by one space.
I have tried the following code:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter weight 1: " + reader.nextDouble());
double weightOne = reader.nextDouble();
System.out.println("Enter weight 2: " + reader.nextDouble());
double weightTwo = reader.nextDouble();
System.out.println("Enter weight 3: " + reader.nextDouble());
double weightThree = reader.nextDouble();
System.out.println("Enter weight 4: " + reader.nextDouble());
double weightFour = reader.nextDouble();
System.out.println("Enter weight 5: " + reader.nextDouble());
double weightFive = reader.nextDouble(); /* Type your code here. */
return;
}
}
I am sorry if my point of confusion is all over the place. But in short I'm having trouble with:
Get user input to register in doubles.
Get those inputs to be stored in an array.
displaying those values in a manner like shown below.
Enter weight 1:
236.0
Enter weight 2:
89.5
Enter weight 3:
142.0
Enter weight 4:
166.3
Enter weight 5:
93.0
You entered: 236.0 89.5 142.0 166.3 93.0
I know this is a little late but I am going through this same activity in zyBooks labs. I noticed the above code is just a little off. Part of the activity is to have the output look like
Enter weight 1: 236
Enter weight 2: 89.5
Enter weight 3: 142
Enter weight 4: 166.3
Enter weight 5: 93
The above code will only out put as
Enter weight: 236
Enter weight: 89.5
Enter weight: 142
Enter weight: 166.3
Enter weight: 93
to fix that you need to do a little tweaking to your output simply by adding the index into your print statement as so
for (i = 0; i < MyArray.length; i = ++i) {
System.out.println("Enter value " + (i + 1) + ": ");
MyArray[i] = reader.nextDouble();
}
You need to add 1 to the index otherwise you'd start at 0 and end at 4. I have provided my code below for anyone thats needing some extra help with this assignment. It did pass all 6 checks 100% though it may not be the most efficient.
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i;
int x;
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.println("Enter weight " + (i + 1) + ": ");
userVals[i] = scnr.nextDouble();
}
System.out.println("");
System.out.print("You entered: ");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.print(userVals[i] + " ");
}
System.out.println("");
double totalWeight = 0.0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
totalWeight += userVals[i];
}
System.out.println("Total weight: " + totalWeight);
double averageWeight = 0.0;
averageWeight = totalWeight / NUM_ELEMENTS;
System.out.println("Average weight: " + averageWeight);
double maxWeight = userVals[0];
for (i =0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] > maxWeight) {
maxWeight = userVals[i];
}
}
System.out.println("Max weight: " + maxWeight);
return;
}
}
here is some code that passed
import java.util.Scanner; //import the scanner for our user inputs
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double [] userVals = new double[NUM_ELEMENTS];
int i; // Declaring variable i to use in for loop
double sumVal; // Declaring sum variable to be used when calculating sum
double maxVal; // Declaring maxVal variable to calculate max weight
for (i = 0; i < userVals.length; ++i) { // for loop that prompts and grabs user input to be used in array
userVals[i] = scnr.nextDouble();
System.out.println("Enter weight " + (i + 1) + ": ");
}
System.out.println(); // Creating new lines to match output of the template in zybooks
System.out.print("You entered: ");
for (i = 0; i < userVals.length; ++i) { // for loop that prints the users input
System.out.print(userVals[i] + " ");
}
// for loop that calculates sum of users input "Total weight"
sumVal = 0.0;
for (i = 0; i < userVals.length; ++i) {
sumVal = sumVal + userVals[i];
}
System.out.println(); // Prints the total weight to match zybooks template
System.out.print("Total weight: " + sumVal);
System.out.println(); // Calculates and Prints Average weight to match zybooks template
System.out.print("Average weight: " + (sumVal / NUM_ELEMENTS));
System.out.println(); // Print statement for whitespace to match zybooks template
maxVal = userVals[0]; // Determine max weight, userVal[0] is the max so far
for (i = 0; i < userVals.length; ++i) { // for loop and if statement to calculate max weight
if (userVals[i] > maxVal) {
maxVal = userVals[i];
}
}
System.out.print("Max weight: " + maxVal); // Prints max weight to match output of zybooks template
System.out.println(); // Print statement to match whitespace of zybooks template
return;
}
}
At first create an array:
// create array of doubles including 5 fields
double[] MyArray = new double[5];
And use for loop to iterate over it and store values in it:
for(int x = 0; x < MyArray.length; x = x + 1)
{
System.out.println("Enter value: ");
MyArray[x] = reader.nextDouble();
}
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int peopleNum = 5; // amount of people being weighed
double[] peopleWeight = new double[peopleNum]; // the array
int i;
double sumVal; // all elements added together
double maxVal; // the maximum element
// tell them to fill the array
System.out.println("Enter weight 1:");
System.out.println("Enter weight 2:");
System.out.println("Enter weight 3:");
System.out.println("Enter weight 4:");
System.out.println("Enter weight 5:");
// printing out what they typed
System.out.print("You entered: ");
for (i = 0; i < peopleWeight.length; ++i) {
peopleWeight[i] = scnr.nextDouble();
System.out.print( peopleWeight[i] + " ");
}
System.out.println(""); // adding all elements together
sumVal = 0;
for (i = 0; i < peopleWeight.length; ++i) {
sumVal = sumVal + peopleWeight[i] ;
}
maxVal = 0; // getting the max value
for (i = 0; i < peopleWeight.length; ++i) {
if (peopleWeight[i] > maxVal) {
maxVal = peopleWeight[i];
}
} // the printing format
System.out.println("");
System.out.println("Total weight: " + sumVal);
System.out.print("Average weight: ");
System.out.println(sumVal / 5);
System.out.print("Max weight: ");
System.out.println(maxVal);
I'm having a problem with counting which is continuation of this question. I am not really a math person so it's really hard for me to figure out this subset sum problem which was suggested as resolution.
I'm having 4 ArrayList in which I hold data: alId, alTransaction, alNumber, alPrice
Type | Transaction | Number | Price
8 | Buy | 95.00000000 | 305.00000000
8 | Buy | 126.00000000 | 305.00000000
8 | Buy | 93.00000000 | 306.00000000
8 | Transfer out | 221.00000000 | 305.00000000
8 | Transfer in | 221.00000000 | 305.00000000
8 | Sell | 93.00000000 | 360.00000000
8 | Sell | 95.00000000 | 360.00000000
8 | Sell | 126.00000000 | 360.00000000
8 | Buy | 276.00000000 | 380.00000000
In the end I'm trying to get what's left for customer and what's left I put into 3 array lists:
- alNewHowMuch (corresponds to alNumber),
- alNewPrice (corresponds to alPrice),
- alNewInID (corrseponds to alID)
ArrayList alNewHowMuch = new ArrayList();
ArrayList alNewPrice = new ArrayList();
ArrayList alNewInID = new ArrayList();
for (int i = 0; i < alTransaction.Count; i++) {
string transaction = (string) alTransaction[i];
string id = (string) alID[i];
decimal price = (decimal) alPrice[i];
decimal number = (decimal) alNumber[i];
switch (transaction) {
case "Transfer out":
case "Sell":
int index = alNewHowMuch.IndexOf(number);
if (index != -1) {
alNewHowMuch.RemoveAt(index);
alNewPrice.RemoveAt(index);
alNewInID.RemoveAt(index);
} else {
ArrayList alTemp = new ArrayList();
decimal sum = 0;
for (int j = 0; j < alNewHowMuch.Count; j ++) {
string tempid = (string) alNewInID[j];
decimal tempPrice = (decimal) alNewPrice[j];
decimal tempNumbers = (decimal) alNewHowMuch[j];
if (id == tempid && tempPrice == price) {
alTemp.Add(j);
sum = sum + tempNumbers;
}
}
if (sum == number) {
for (int j = alTemp.Count - 1; j >= 0; j --) {
int tempIndex = (int) alTemp[j];
alNewHowMuch.RemoveAt(tempIndex);
alNewPrice.RemoveAt(tempIndex);
alNewInID.RemoveAt(tempIndex);
}
}
}
break;
case "Transfer In":
case "Buy":
alNewHowMuch.Add(number);
alNewPrice.Add(price);
alNewInID.Add(id);
break;
}
}
Basically I'm adding and removing things from Array depending on Transaction Type, Transaction ID and Numbers. I'm adding numbers to ArrayList like 156, 340 (when it is TransferIn or Buy) etc and then i remove them doing it like 156, 340 (when it's TransferOut, Sell). My solution works for that without a problem. The problem I have is that for some old data employees were entering sum's like 1500 instead of 500+400+100+500. How would I change it so that when there's Sell/TransferOut or Buy/Transfer In and there's no match inside ArrayList it should try to add multiple items from thatArrayList and find elements that combine into aggregate.
Inside my code I tried to resolve that problem with simple summing everything when there's no match (index == 1)
int index = alNewHowMuch.IndexOf(number);
if (index != -1) {
alNewHowMuch.RemoveAt(index);
alNewPrice.RemoveAt(index);
alNewInID.RemoveAt(index);
} else {
ArrayList alTemp = new ArrayList();
decimal sum = 0;
for (int j = 0; j < alNewHowMuch.Count; j ++) {
string tempid = (string) alNewInID[j];
decimal tempPrice = (decimal) alNewPrice[j];
decimal tempNumbers = (decimal) alNewHowMuch[j];
if (id == tempid && tempPrice == price) {
alTemp.Add(j);
sum = sum + tempNumbers;
}
}
if (sum == number) {
for (int j = alTemp.Count - 1; j >= 0; j --) {
int tempIndex = (int) alTemp[j];
alNewHowMuch.RemoveAt(tempIndex);
alNewPrice.RemoveAt(tempIndex);
alNewInID.RemoveAt(tempIndex);
}
}
}
But it only works if certain conditions are met, and fails for the rest.
Edit: Since some of you were so astonished (and blinded) by my polish variable names i translated all of them to english for simplicity and visiblity. Hopefully this will help me to get some help :-)
Here is my algorithm. It runs in O(2^(n/2)) and solves SubsetSum(1000, list-of-1000-ones) in 20 milliseconds. See the comments at the end of IVlad's post.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace SubsetSum
{
class Program
{
static void Main(string[] args)
{
var ns = new List<int>();
for (int i = 0; i < 1000; i++) ns.Add(1);
var s1 = Stopwatch.StartNew();
bool result = SubsetSum(ns, 1000);
s1.Stop();
Console.WriteLine(result);
Console.WriteLine(s1.Elapsed);
Console.Read();
}
static bool SubsetSum(ist<int> nums, int targetL)
{
var left = new List<int> { 0 };
var right = new List<int> { 0 };
foreach (var n in nums)
{
if (left.Count < right.Count) left = Insert(n, left);
else right = Insert(n, right);
}
int lefti = 0, righti = right.Count - 1;
while (lefti < left.Count && righti >= 0)
{
int s = left[lefti] + right[righti];
if (s < target) lefti++;
else if (s > target) righti--;
else return true;
}
return false;
}
static List<int> Insert(int num, List<int> nums)
{
var result = new List<int>();
int lefti = 0, left = nums[0]+num;
for (var righti = 0; righti < nums.Count; righti++)
{
int right = nums[righti];
while (left < right)
{
result.Add(left);
left = nums[++lefti] + num;
}
if (right != left) result.Add(right);
}
while (lefti < nums.Count) result.Add(nums[lefti++] + num);
return result;
}
}
}
And here is an improved version that prunes the sets:
static bool SubsetSum(List<int> nums, int target)
{
var remainingSum = nums.Sum();
var left = new List<int> { 0 };
var right = new List<int> { 0 };
foreach (var n in nums)
{
if (left.Count == 0 || right.Count == 0) return false;
remainingSum -= n;
if (left.Count < right.Count) left = Insert(n, left, target - remainingSum - right.Last(), target);
else right = Insert(n, right, target - remainingSum - left.Last(), target);
}
int lefti = 0, righti = right.Count - 1;
while (lefti < left.Count && righti >= 0)
{
int s = left[lefti] + right[righti];
if (s < target) lefti++;
else if (s > target) righti--;
else return true;
}
return false;
}
static List<int> Insert(int num, List<int> nums, int min, int max)
{
var result = new List<int>();
int lefti = 0, left = nums[0]+num;
for (var righti = 0; righti < nums.Count; righti++)
{
int right = nums[righti];
while (left < right)
{
if (min <= left && left <= max) result.Add(left);
left = nums[++lefti] + num;
}
if (right != left && min <= right && right <= max) result.Add(right);
}
while (lefti < nums.Count)
{
left = nums[lefti++] + num;
if (min <= left && left <= max) result.Add(left);
}
return result;
}
This last one solved the problem with 100000 ones in about 5 milliseconds (but this is a best case of the algorithm, with real world data it will be slower).
For your use this algorithm is probably fast enough (and I don't see any obvious improvements). If you enter 10,000 products with a random price between 0 and 20 and your goal is to sum to 500 this is solved in 0.04 seconds on my laptop.
Edit: I just read on Wikipedia that the best known algorithm is O(2^(n/2)*n). This one is O(2^(n/2)). Do I get the Turing Award?
How you should do this depends on a number important things: how many numbers will you have and how big will they be? Also, as far as I understand, your data can change (add / remove numbers etc.), right?. How often do you need to make these queries?
I'll present two solutions. I suggest you use the second, as I suspect it's better for what you need and it's a lot easier to understand.
Solution 1 - dynamic programming
Let S[i] = true if we can make sum i and false otherwise.
S[0] = true // we can always make sum 0: just don't choose any number
S[i] = false for all i != 0
for each number i in your input
for s = MaxSum downto i
if ( S[s - i] == true )
S[s] = true; // if we can make the sum s - i, we can also make the sum s by adding i to the sum s - i.
To get the actual numbers that make up your sum you should keep another vector P[i] = the last number that was used to make sum i. You would update this accordingly in the if condition above.
The time complexity of this is O(numberOfNumbers * maxSumOfAllNumbers), which is pretty bad, especially since you have to rerun this algorithm whenever your data changes. It's also slow for even one run as long as your numbers can be very big and you can have a lot of them. In fact, "a lot" is misleading. If you have 100 numbers and each number can be as big as 10 000, you will do roughly 100 * 10 000 = 1 000 000 operations each time your data changes.
It's a good solution to know, but not really useful in practice, or at least not in your case I think.
He's some C# for the approach I suggest:
class Program
{
static void Main(string[] args)
{
List<int> testList = new List<int>();
for (int i = 0; i < 1000; ++i)
{
testList.Add(1);
}
Console.WriteLine(SubsetSum.Find(testList, 1000));
foreach (int index in SubsetSum.GetLastResult(1000))
{
Console.WriteLine(index);
}
}
}
static class SubsetSum
{
private static Dictionary<int, bool> memo;
private static Dictionary<int, KeyValuePair<int, int>> prev;
static SubsetSum()
{
memo = new Dictionary<int, bool>();
prev = new Dictionary<int, KeyValuePair<int, int>>();
}
public static bool Find(List<int> inputArray, int sum)
{
memo.Clear();
prev.Clear();
memo[0] = true;
prev[0] = new KeyValuePair<int,int>(-1, 0);
for (int i = 0; i < inputArray.Count; ++i)
{
int num = inputArray[i];
for (int s = sum; s >= num; --s)
{
if (memo.ContainsKey(s - num) && memo[s - num] == true)
{
memo[s] = true;
if (!prev.ContainsKey(s))
{
prev[s] = new KeyValuePair<int,int>(i, num);
}
}
}
}
return memo.ContainsKey(sum) && memo[sum];
}
public static IEnumerable<int> GetLastResult(int sum)
{
while (prev[sum].Key != -1)
{
yield return prev[sum].Key;
sum -= prev[sum].Value;
}
}
}
You should do some error checking perhaps, and maybe store the last sum in the class so as not to allow the possibility of calling GetLastResult with a different sum than the sum Find was last called with. Anyway, this is the idea.
Solution 2 - randomized algorithm
Now, this is easier. Keep two lists: usedNums and unusedNums. Also keep a variable usedSum that, at any point in time, contains the sum of all the numbers in the usedNums list.
Whenever you need to insert a number into your set, also add it to one of the two lists (doesn't matter which, but do it randomly so there's a relatively even distribution). Update usedSum accordingly.
Whenever you need to remove a number from your set, find out which of the two lists it's in. You can do this with a linear seach as long as you don't have a lot (this time a lot means over 10 000, maybe even 100 000 on a fast computer and assuming you don't do this operation often and in fast succession. Anyway, the linear search can be optimized if you need it to be.). Once you have found the number, remove it from the list. Update usedSum accordingly.
Whenever you need to find if there are numbers in your set that sum to a number S, use this algorithm:
while S != usedSum
if S > usedSum // our current usedSum is too small
move a random number from unusedNums to usedNums and update usedSum
else // our current usedSum is too big
move a random number from usedNums to unusedNums and update usedSum
At the end of the algorithm, the list usedNums will give you the numbers whose sum is S.
This algorithm should be good for what you need, I think. It handles changes to the dataset very well and works well for a high number count. It also doesn't depend on how big the numbers are, which is very useful if you have big numbers.
Please post if you have any questions.
I have seen this question for other languages but not for AS3... and I'm having a hard time understanding it...
I need to generate 3 numbers, randomly, from 0 to 2, but they cannot repeat (as in 000, 001, 222, 212 etc) and they cannot be in the correct order (0,1,2)...
Im using
for (var u: int = 0; u < 3; u++)
{
mcCor = new CorDaCarta();
mcCor.x = larguraTrio + (mcCor.width + 5) * (u % 3);
mcCor.y = alturaTrio + (mcCor.height + 5) * (Math.floor(u / 3));
mcCor.gotoAndStop((Math.random() * (2 - u + 1) + u) | 0); // random w/ repeats
//mcCor.gotoAndStop(Math.floor(Math.random() * (2 - u + 1) + u)); // random w/ repeats
//mcCor.gotoAndStop((Math.random() * 3) | 0); // crap....
//mcCor.gotoAndStop(Math.round(Math.random()*u)); // 1,1,1
//mcCor.gotoAndStop(u + 1); // 1,2,3
mcCor.buttonMode = true;
mcCor.addEventListener(MouseEvent.CLICK, cliquetrio);
mcExplic.addChild(mcCor);
trio.push(mcCor);
}
those are the codes i've been trying.... best one so far is the active one (without the //), but it still gives me duplicates (as 1,1,1) and still has a small chance to come 0,1,2....
BTW, what I want is to mcCor to gotoAndStop on frames 1, 2 or 3....without repeating, so THE USER can put it on the right order (1,2,3 or (u= 0,1,2), thats why I add + 1 sometimes there)
any thoughts?? =)
I've found that one way to ensure random, unique numbers is to store the possible numbers in an array, and then sort them using a "random" sort:
// store the numbers 0, 1, 2 in an array
var sortedNumbers:Array = [];
for(var i:int = 0; i < 3; i++)
{
sortedNumbers.push(i);
}
var unsortedNumbers:Array = sortedNumbers.slice(); // make a copy of the sorted numbers
trace(sortedNumbers); // 0,1,2
trace(unsortedNumbers); // 0,1,2
// randomly sort array until it no longer matches the sorted array
while(sortedNumbers.join() == unsortedNumbers.join())
{
unsortedNumbers.sort(function (a:int, b:int):int { return Math.random() > .5 ? -1 : 1; });
}
trace(unsortedNumbers); // [1,0,2], [2,1,0], [0,1,2], etc
for (var u: int = 0; u < 3; u++)
{
mcCor = new CorDaCarta();
mcCor.x = larguraTrio + (mcCor.width + 5) * (u % 3);
mcCor.y = alturaTrio + (mcCor.height + 5) * (Math.floor(u / 3));
// grab the corresponding value from the unsorted array
mcCor.gotoAndStop(unsortedNumbers[u] + 1);
mcCor.buttonMode = true;
mcCor.addEventListener(MouseEvent.CLICK, cliquetrio);
mcExplic.addChild(mcCor);
trio.push(mcCor);
}
Marcela is right. Approach with an Array is widely used for such task. Of course, you will need to check 0, 1, 2 sequence and this will be ugly, but in common code to get the random sequence of integers can look like this:
function getRandomSequence(min:int, max:int):Array
{
if (min > max) throw new Error("Max value should be greater than Min value!");
if (min == max) return [min];
var values:Array = [];
for (var i:int = min; i <= max; i++) values.push(i);
var result:Array = [];
while (values.length > 0) result = result.concat(values.splice(Math.floor(Math.random() * values.length), 1));
return result;
}
for (var i:uint = 0; i < 10; i++)
{
trace(getRandomSequence(1, 10));
}
You will get something like that:
2,9,3,8,10,6,5,1,4,7
6,1,2,4,8,9,5,10,7,3
3,9,10,6,8,2,5,4,1,7
7,6,1,4,3,8,9,2,10,5
4,6,7,1,3,2,9,10,8,5
3,10,5,9,1,7,2,4,8,6
1,7,9,6,10,3,4,5,2,8
4,10,8,9,3,2,6,1,7,5
1,7,8,9,10,6,4,3,2,5
7,5,4,2,8,6,10,3,9,1
I created this for you. It is working but it can be optimized...
Hope is good for you.
var arr : Array = [];
var r : int;
for (var i: int = 0; i < 3; i++){
r=rand(0,2);
if(i == 1){
if(arr[0] == r){
i--;
continue;
}
if(arr[0] == 0){
if(r==1){
i--;
continue;
}
}
}else if(i==2){
if(arr[0] == r || arr[1] == r){
i--;
continue;
}
}
arr[i] = r;
}
trace(arr);
for(var i=0;i<3;i++){
mcCor = new CorDaCarta();
mcCor.x = larguraTrio + (mcCor.width + 5) * (i % 3);
mcCor.y = alturaTrio + (mcCor.height + 5) * (Math.floor(i / 3));
mcCor.gotoAndStop(arr[i]);
mcCor.buttonMode = true;
mcCor.addEventListener(MouseEvent.CLICK, cliquetrio);
mcExplic.addChild(mcCor);
trio.push(mcCor);
}
function rand(min:int, max:int):int {
return Math.round(Math.random() * (max - min) + min);
}
try this...