I am developing a game that has a winning combination array:
var allwinning = [
['000','010','020'],
['000','100','200'],
['000','001','002'],
['000','101','202'],
['000','011','022'],
['000','110','220']];
The player will need to pick more than 3 numbers randomly. If all numbers are within any of the combinations in allwinning, the player wins.
For example, if the player picks '111','110','000','220', the player will win because allwinning[5] has the combination['000','110','220'].
My question is, what is the best way to do this winning loop? I cannot figure out the optimum way to do this.
Currently, I have a playerpick array to keep what player had picked and possiblewin array:
var playerpick = new Array(['111','110','000','220']);
var playerpicksingle = playerpick[0];
var possiblewin = new Array([]);
Then I go through a loop to capture out the possible win combination first:
for(var i=0 ; i < allwinning.length - 1 ; i++)
{
for(var j=0 ; j <3 ; j++)
{
if(allwinning[i][j]==playerpicksingle)
{
possiblewin.Push(allwinning[i]);
}
}
}
Then I am stuck at this point. I really don't know what else to do.
I can think of two ways. One requires you to change your data structure and the other doesn't.
Without changes:
Sort the user input:
pickedNumbers.sort();
and start comparing. By sorting the values beforehand you know when you can back out and continue with the next set of numbers, i.e. you can back out early and don't have to compare all the values (in the average case).
function wins(picked, winning) {
var winningSet = [];
for (var i = 0; i < winning.length && winningSet.length < 3; i++) {
var set = winning[i];
winningSet = [];
var j = 0;
var k = 0;
while (j < set.length && k < picked.length && winningSet.length < 3) {
if (picked[k] === set[j]) {
winningSet.push(set[j]);
j++; // advance to next element in winning set
} else if (picked[k] > set[j]) {
// continue with the next set
break;
}
// maybe the next element in players picks will match
k++;
}
}
return winningSet.length === 3 ? winningSet : false;
}
The worst case scenario of this solution is O(n*m*l), but since the input is sorted, the average case will be better.
DEMO
With Array#some and Array#every the code becomes much more concise, though it looses the advantage of using sorted input. If your arrays are small it won't make a difference though:
function wins(picked, winning) {
return winning.some(function(set) {
return set.every(function(val) {
return picked.indexOf(val) !== -1;
});
});
}
It also won't give you the actual numbers that matched. The runtime is the same.
The second way would be to build some kind of trie instead of using an array of arrays:
var allwinning = {
'000': {
'010': {
'020': true
},
'100': {
'200': true
},
// ...
}
};
The structure should also be sorted, i.e. the keys of a level are all smaller then the keys of its sublevel etc.
Sort the user input as well and iterate over it. Whenever you found a matching key, you go one level deeper until you have three matches:
function wins(picked, winning) {
var winningSet = [];
for (var i = 0; i < picked.length && winningSet.length < 3; i++) {
if (picked[i] in winning) {
winningSet.push(picked[i]);
winning = winning[picked[i]];
}
}
return winningSet.length === 3 ? winningSet : false;
}
This solution has the worst case scenario of O(n), where n is the number of values the user picked (not taking into account the time it takes to test whether an object contains a specific property name. Often this is assumed to constant).
DEMO
Related
So i'm having trouble trying to build out an excel sheet faster than 20 seconds. I'm using the below to compare 3 different arrays to then print out the answer i need.
for (let i = 0; i < this.arrayNumberOne[0].length; i++) {
let orangeOne = this.arrayNumberOne[0][i]['item_1'];
let orangeTwo = this.arrayNumberOne[0][i]['item_2'];
let orangeThree = orangeOne.concat(orangeTwo)
for (let k = 0; k < this.arrayNumberTwo[0].length; k++) {
let appleOne = this.arrayNumberTwo[0][k]['item_1'];
for (let j = 0; j < this.arrayNumberThree[0].length; j++) {
let grapeOne = this.arrayNumberThree[0][j]['item_1'];
let grapeTwo = this.arrayNumberThree[0][j]['item_2'];
let grapeThree = this.arrayNumberThree[0][j]['item_3'];
if (orangeThree == grapeOne && appleOne == grapeTwo) {
if (grapeThree == null || grapeThree == '') {
// print to response to excel
}
else if (grapeThree == 'sells') {
// print stuff to excel
}
else if (grapeThree == 'buys') {
// print stuff to excel
}
}
}
}
}
I was looking at hashmaps and interfaces, but im not quite sure how i could apply that here. I would appreciate any alternatives to making the above faster.
Edit:
Playground Link
What sets off a red flag here is that you have 3 nested loops, but your data is 2D, so you would expect at most 2 nested loops (one for X and one for Y). What you want to focus on is that the process for getting the value of each cell should be as fast as possible, since that is what needs to happens to largest number of times.
The key here is pre-process your values (what goes in the cells of your spreadsheet, buy/sell/blank) in a way that makes it very quick look those up.
For example:
// Index all actions by player id and item name
const indexedActions: {
[playerId: string]: {
[itemCatName: string]: string
}
} = {}
// Loop through all actions once to index them.
for (const {playerId, itemCatName, action} of actions) {
if (!indexedActions[playerId]) indexedActions[playerId] = {}
indexedActions[playerId][itemCatName] = action
}
After that runs you'll have data like:
{
"12": {
"potionsmall-potion": 'buy'
// etc...
}
// etc...
}
That's important because now looking up any cell is as easy as:
indexedActions[playerId][itemName]
Which lets you completely remove that most inner loop.
// Loop through items
for (let i = 0; i < items.length; i++) {
let itemCat = items[i]['itemCategory']
let itemNam = items[i]['itemName']
let combineCat = itemCat.concat(itemNam)
// Loop through players
for (let k = 0; k < players.length; k++) {
let playerIdentify = players[k]['playerId']
// Lookup what this player did with this item
const actionToDo = indexedActions[playerIdentify][combineCat]
// do stuff with action
}
}
Before Optimization
for every item
for every player
for every action
doLogic()
Here "doLogic" is executed itemCount * playerCount * actionCount times.
After Optimization
for every action
index each action
for every item
for every player
doLogic()
Now we do a little more work up front, but doLogic is only executed itemCount * playerCount times, which is a huge improvement.
And as a bonus it's less code and easier to read!
See playground
I'm not entirely sure whats going on here. When you shoot all three bullets and the last one leaves the screen the "asteroids" array also resets.
EDIT:
Is it because the bullets array ends up being spliced to an undefined when they all leave the screen? Or will it return the base empty array? Even then, it doesn't explain why the asteroids array is voided as well. I also found that the asteroids don't even start falling unless I've shot at least once.
Code on p5web editor
What is it causing this to happen? This is the first time I've coded something this large, code amount wise, but I made sure to use obvious variable names for the most part.
The problem is in your asteroids class:
check(bullets) {
for (let i = 0; i < bullets.length; i++) {
if (dist(bullets[i].x, bullets[i].y, this.pos.x, this.pos.y) < this.r) {
return false;
} else {
return true;
}
}
}
If there are no bullets to check, this function returns undefined implicitly, which is taken as falsey by the calling code, which promptly destroys the asteroid as if it had collided with a bullet.
Also, if there are bullets to check and the first one happens to not collide, the loop breaks prematurely with else { return true; }, possibly missing collisions.
Change it to:
check(bullets) {
for (let i = 0; i < bullets.length; i++) {
if (dist(bullets[i].x, bullets[i].y, this.pos.x, this.pos.y) < this.r) {
return false;
}
}
return true; // no collisions (or bullets.length === 0)
}
Having said this, the function name check is pretty unclear. I'd rename it as collidesWith(bullets) and invert the boolean--it makes more sense to say "true, yes, we did collide with a bullet" than "false, yes, we did collide with a bullet". We can also make use of the for ... of loop construct. This gives us:
collidesWith(bullets) {
for (const bullet of bullets) {
if (dist(bullet.x, bullet.y, this.pos.x, this.pos.y) < this.r) {
return true;
}
}
return false;
}
You could shorten this further to:
collidesWith(bullets) {
return bullets.some(e => dist(e.x, e.y, this.pos.x, this.pos.y) < this.r);
}
Similarly, I'd change bullet.check() to bullet.outOfBounds() or similar.
Another tip: iterate in reverse over any arrays you plan to slice the current element from:
for (let j = asteroids.length - 1; j >= 0; j--) {
// code that could call `.splice(j, 1)`
}
Otherwise, after splicing, your loop will skip an element and you might miss a collision.
A minor design point, but player.controls() seems strange--why should the player be responsible for listening for keypresses? I'd listen in the keyPressed() function and send the changes to update the player position from there. I'd also break up draw into smaller functions. But these are minor design decisions so the above is enough to get you rolling.
Here's a first revision for the draw function, adjusted to match the modified booleans:
function draw() {
background(0);
scene();
if (tick <= 0) {
if (asteroids.length < asteroidsLimit) {
asteroids.push(new Asteroid());
}
tick = 60;
}
for (let i = asteroids.length - 1; i >= 0; i--) {
if (asteroids[i].collidesWith(bullets)) {
asteroids.splice(i, 1);
}
else {
asteroids[i].update();
asteroids[i].display();
}
}
for (let i = bullets.length - 1; i >= 0; i--) {
if (bullets[i].outOfBounds()) {
bullets.splice(i, 1);
}
else {
bullets[i].update();
bullets[i].display();
}
}
image(ship, player.x, player.y);
player.controls();
tick--;
}
I have 2 arrays, 1 is a master (bookArray) and the other an update list (stockBooksArray). I use the loop below to import new data into waster array using a unique record (isbn) that exists in both arrays.
Is there a way to improve the performance of the loop below?
The update array can contain a different count to the master, sometimes more, sometimes less.
for i in 0...stockBooksArray.count {
let StockFiltered = stockBooksArray.filter{$0.isbn == bookArray[i].isbn}
if StockFiltered.count != 0 {
bookArray[i].stockAmount = StockFiltered[0].Stock
bookArray[i].unitCost = StockFiltered[0].Cost
bookArray[i].dues = StockFiltered[0].dues
bookArray[i].stockRRP = StockFiltered[0].RRP
}
}
Thanks,
Anthony
Yes there is. Right now you are looping through the bookArray array once for every stockBooksArray object. That's O(N*M) which is pretty bad.
Instead, if you can sort both arrays by ISBN, then you can step through both at the same time, visiting each element only once which would be O(N). Considerably faster, even if you include the time to sort them.
I threw the code below together pretty quick. It assumes that both arrays are sorted by isbn. I think you will find this considerably faster.
var j = 0
for book in stockBooksArray {
while bookArray[j].isbn < book.isbn && j < bookArray.count {
++j;
}
if j == bookArray.count {
break
}
else if bookArray[j].isbn == book.isbn {
bookArray[j].stockAmount = StockFiltered[0].Stock
bookArray[j].unitCost = StockFiltered[0].Cost
bookArray[j].dues = StockFiltered[0].dues
bookArray[j].stockRRP = StockFiltered[0].RRP
}
}
If you are just adding new ones you could get an NSMutableSet of the ISBNs for each, perform a set minusSet: operation removing the bookArray ISBNs from stockBooksArray and then just add the resulting ISBNs to bookArray.
Untested concept code, convert to Swift as needed:
NSMutableSet *stockBooksSet = NSMutableSet setWithArray:[stockBooksSet valueForKey:#"isbn"];
NSSet *booksSet = NSSet setWithArray:[bookArray valueForKey:#"isbn"];
[stockBooksSet minusSet: booksSet];
for (NSString *isbn in stockBooksSet) {
// add book with ism to booksSet
}
Updated code using Daniel T. method.
bookArray.sort { (lhs, rhs) in return lhs.isbn < rhs.isbn }
stockBooksArray.sort { (lhs, rhs) in return lhs.isbn < rhs.isbn }
var j = 0
for book in stockBooksArray {
while bookArray[j].isbn < book.isbn && j < bookArray.count {
++j
}
if j == bookArray.count {
break
}
else if bookArray[j].isbn == book.isbn {
bookArray[j].stockAmount = book.Stock
bookArray[j].unitCost = book.Cost
bookArray[j].dues = book.dues
bookArray[j].stockRRP = book.RRP
}
}
From 5-6 seconds on iPad2 to almost instant.
Many thanks,
Anthony
I'm currently creating a small flash game using ActionScript and after receiving help for another issue I had on here, I've encountered another one when moving onto a different part of it.
This is the code I currently have:
var asteroidSpeed = 5;
var soundExplosion:Sound = new ExplosionSound();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKDown);
var newLaser:Array = new Array();
function onKDown(e:KeyboardEvent):void {
keys[e.keyCode] = true;
if (e.keyCode == 32) {
/*laser.x = player.x + player.width/2 - laser.width/2;
laser.y = player.y;
addChild(laser);*/
for (var count=0; count < 4; count++) {
newLaser[count] = new shipLaser();
newLaser[count].x = player.x + player.width/2 - newLaser.width/2;
newLaser[count].y = player.y;
addChild(newLaser[count]);
}
}
}
var spawnTimer:Timer = new Timer(3000); //timer will tick every 3 seconds
spawnTimer.addEventListener(TimerEvent.TIMER, spawn, false, 0, true); //let's run the spawn function every timer tick
spawnTimer.start();
var spawnPoints:Array = [0,100,200,300,400,500,550]; //your list of spawn x locations
var spawnAmount:int = 4; //how many asteroids to have on the screen at once (you could increase this over time to make it more difficult)
var asteroids:Vector.<asteroidOne> = new Vector.<asteroidOne>(); //the array for your asteroids - changed to vector for possible performance and code hint improvement (basically the same as Array but every object has to be of the specified type)
spawn(); // calling it immediately
//calling this will spawn as many new asteroids as are needed to reach the given amount
function spawn(e:Event = null):void {
if(asteroids.length >= spawnAmount) return; //let's not bother running any of the code below if no new asteroids are needed
spawnPoints.sort(randomizeArray); //lets randomize the spwanPoints
var spawnIndex:int = 0;
var a:asteroidOne; //var to hold the asteroid every loop
while (asteroids.length < spawnAmount) {
a = new asteroidOne();
a.x = spawnPoints[spawnIndex];
spawnIndex++; //incriment the spawn index
if (spawnIndex >= spawnPoints.length) spawnIndex = 0; //if the index is out of range of the amount of items in the array, go back to the start
a.y = -50;
asteroids.push(a); //add it to the array/vector
addChild(a); //add it to the display
}
}
player.addEventListener(Event.ENTER_FRAME, obstacleMove);
function obstacleMove(evt:Event):void {
for (var i:int = 0; i < asteroids.length;i++) {
asteroids[i].y += asteroidSpeed;
if (asteroids[i].y > stage.stageHeight || asteroids[i].x > stage.stageWidth || asteroids[i].x < -asteroids[i].width || asteroids[i].y < -asteroids[i].height) {
//object is out of the bounds of the stage, let's remove it
removeChild(asteroids[i]); //remove it from the display
asteroids.splice(i, 1); //remove it from the array/vector
continue; //move on to the next iteration in the for loop
}
if (player.hitTestObject(asteroids[i])) {
trace("HIT");
removeChild(asteroids[i]);
asteroids.splice(i,1);
removeChild(player);
// will add end-game trigger here soon.
}
}
}
function randomizeArray(a:*, b:*):int {
return (Math.random() < .5 ) ? 1 : -1;
}
player.addEventListener(Event.ENTER_FRAME, laserCollision);
function laserCollision(evt:Event):void {
for (var i in newLaser) {
for (var a in asteroids) {
if (asteroids[a].hitTestObject(newLaser[i])) {
trace("BOOM!");
var soundExplosion:Sound = new ExplosionSound();
var channel1:SoundChannel = soundExplosion.play();
removeChild(newLaser[i]);
removeChild(asteroids[a]);
}
}
}
}
addEventListener(Event.ENTER_FRAME, laserEnter);
function laserEnter(event:Event):void {
for (var i in newLaser) {
newLaser[i].y -= laserSpeed;
// Moves the laser up the screen
if(newLaser[i].y == 0) {
removeChild(newLaser[i]);
}
}
}
What I want to do is when an instance from the newLaser array collides with an instance of the asteroids array, to remove both from the scene / indexes (but only the two that collided and not all of the ones on the scene).
Currently, when a laser hits an asteroid, it removes the asteroid but not the laser and one of the asteroids on the current row stops moving and then the next row of asteroids spawns but does not move down.
I get this error too:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at _8_fla::MainTimeline/obstacleMove()
Any help would be greatly appreciated.
You error, is likely because you are running 3 separate enter frame handlers in the same scope, and removing items from arrays and display lists (that are referenced in multiple enter frame handlers). So you asteroid is removed from the display list in one, and then you try to remove it again in another.
There are also a whole lot of other issues with your code that will cause errors and undesired results. Things like for(var i in newLasers) - in that kind of loop, i will refer to the actual laser object not the index of the array. I've re-factored your code and added lots of code comments to hopefully give you an idea of where you were going wrong:
var spawnTimer:Timer = new Timer(3000); //timer will tick every 3 seconds
var spawnPoints:Array = [0, 100, 200, 300, 400, 500, 550]; //your list of spawn x locations
var spawnAmount:int = 4; //how many asteroids to have on the screen at once (you could increase this over time to make it more difficult)
var asteroidSpeed = 5;
var asteroids:Vector.<asteroidOne> = new Vector.<asteroidOne>(); //the array for your asteroids - changed to vector for possible performance and code hint improvement (basically the same as Array but every object has to be of the specified type)
var lasers:Vector.<shipLaser> = new shipLaser(); //the array of lasers
var maxLasers:int = 4; //the maximum amount lasers allowed at any given time
var soundExplosion:Sound = new ExplosionSound();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKDown);
player.addEventListener(Event.ENTER_FRAME, gameLoop);
spawnTimer.addEventListener(TimerEvent.TIMER, spawn, false, 0, true); //let's run the spawn function every timer tick
spawnTimer.start(); //start the spawn timer
spawn(); // calling it immediately
function onKDown(e:KeyboardEvent):void{
if (e.keyCode == 32) {
//create ONE laser per button push (instead of 4 identical lasers)
if(lasers.length < maxLasers){ //if player hasn't reached the maximum amount of lasers available
var tmpLaser:shipLaser = new shipLaser();
tmpLaser.x = player.x + player.width / 2 - tmpLaser.width / 2;
tmpLaser.y = player.y;
addChild(tmpLaser);
lasers.push(tmpLaser);
}
}
}
//calling this will spawn as many new asteroids as are needed to reach the given amount
function spawn(e:Event = null):void {
if (asteroids.length >= spawnAmount)
return; //let's not bother running any of the code below if no new asteroids are needed
spawnPoints.sort(randomizeArray); //lets randomize the spwanPoints
var spawnIndex:int = 0;
var a:asteroidOne; //var to hold the asteroid every loop
while (asteroids.length < spawnAmount)
{
a = new asteroidOne();
a.x = spawnPoints[spawnIndex];
spawnIndex++; //incriment the spawn index
if (spawnIndex >= spawnPoints.length)
spawnIndex = 0; //if the index is out of range of the amount of items in the array, go back to the start
a.y = -50;
asteroids.push(a); //add it to the array/vector
addChild(a); //add it to the display
}
}
function gameLoop(e:Event):void {
//LOOP through all the asteroids, give it a label (asteroidLoop) so we can break/continue it inside other loops
asteroidLoop: for (var i:int = 0; i < asteroids.length; i++) {
//check if asteroid is out of bounds
if (asteroids[i].y > stage.stageHeight || asteroids[i].x > stage.stageWidth || asteroids[i].x < -asteroids[i].width || asteroids[i].y < -asteroids[i].height) {
//object is out of the bounds of the stage, let's remove it
removeChild(asteroids[i]); //remove it from the display
asteroids.splice(i, 1); //remove it from the array/vector
continue; //forget the rest of the code below and move on to the next iteration in the for loop since the asteroid is gone
}
//check if any lasers are colliding with this asteroid
for (var j:int = lasers.length-1; j >= 0;j--) { //iterate over all lasers backwards
if (asteroids[i].hitTestObject(lasers[j])){
trace("BOOM!");
var soundExplosion:Sound = new ExplosionSound();
var channel1:SoundChannel = soundExplosion.play();
//remove the asteroid
removeChild(asteroids[i]); //remove it from the display
asteroids.splice(i, 1); //remove it from the array/vector
//remove the laser
removeChild(lasers[j]);
lasers.splice(j, 1);
continue asteroidLoop; //break completely out of this inner for-loop (lasers) since the asteroid in the outer loop was removed, and move on to the next asteroid
}
}
//check if this asteroid collides with the player
if (player.hitTestObject(asteroids[i])){
trace("HIT");
//remove the asteroid
removeChild(asteroids[i]); //remove it from the display
asteroids.splice(i, 1); //remove it from the array/vector
removeChild(player);
spawnTimer.stop(); //stop spawning new asteroids
//will add end-game trigger here soon.
break; //break completely out of the asteroid loop if it's game over (as there's no point in checking the rest of the asteroids)
}
//we've made it this far, so let's just move this asteroid
asteroids[i].y += asteroidSpeed;
}
for (var i:int = lasers.length-1; i >= 0;i--) { //iterate backwards
lasers[i].y -= laserSpeed;
// Moves the laser up the screen
if (lasers[i].y <= 0){ //make this less than or equal to 0
removeChild(lasers[i]); //remove the laser from the display list
lasers.splice(i, 1); //remove the laser from the array
}
}
}
function randomizeArray(a:*, b:*):int {
return (Math.random() < .5) ? 1 : -1;
}
I have two arrays, namely combo and truecombo. The user fills the combo with MovieClips by clicking on various buttons on the stage, truecombo is the correct combination.
At any given point (enterFrame) Flash is checking whether the two are the same, if yes, then do some stuff. For the time being this is my code (altered several times, like with Typecasting the indices, adding .parent at the end of combo[o] etc. 2 things will happen, either one or the other.
Either the statement will not be satisfied, at which point the adding and chopping of the combo array will continue, or the condition will be instantly met when combo.length = 6. Check my code.
UPDATE: I have a dropbox file with my current code. Click this for FLA link and here is the SWF link stripped down as always for ease and security.
/*stage.*/addEventListener(Event.ENTER_FRAME, checkthis);
function checkthis(e:Event)
{
for(var o:int=0;o<= combo.length; o++)
{
if((combo[o] == truecombo[o]) && (combo.length==truecombo.length))
{
equal=true;
}
}
if (equal==true)
{
stage.removeEventListener(Event.ENTER_FRAME, checkthis);
endSeq();
}
}
function endSeq():void
{
bravo.play();
for (var i:int = 0; i < combo.length; i++)
{
var element:DisplayObject = combo[i];
element.parent.removeChild(element);
}
firebb.gotoAndPlay(2);
windbb.gotoAndPlay(2);
spiritbb.gotoAndPlay(2);
earthbb.gotoAndPlay(2);
}
This is how I push my new elements to the combo array.
function add(element:DisplayObject)
{
twist.gotoAndPlay(2);
element.width = WIDTH;
element.height = HEIGHT;
if (this.combo.length >= MAX_ELEMENTS)
{
removeChild(this.combo.shift());
}
this.combo.push(element as DisplayObject);
this.addChild(element);
this.reorder();
}
function reorder()
{
for (var i:int = 0; i < combo.length; i++)
{
var element:DisplayObject = combo[i];
element.x = OFFSET_X + (i * SEP_X);
element.y = OFFSET_Y;
}
}
And this is how I have my truecombo and its contents created.
var fireb:firebtn = new firebtn();
var spiritb:spiritbtn = new spiritbtn();
var earthb:earthbtn = new earthbtn();
var windb:windbtn = new windbtn();
var combo:Array=new Array();
const truecombo:Array = [fireb,windb,spiritb,windb,earthb,fireb];
Sorry for the lack of comments, I'd guess it's pretty self-explanatory. Thanks in advance.
I believe combo[o] & truecombo[o] are two instances of the same class & you want them to be matched. If that is the case you may consider :
getQualifiedClassName(combo[o]) == getQualifiedClassName(truecombo[o])
To match the way you did, you must ensure the objects lying inside truecombo be referring to the same ones on stage & not new instances.
EDIT:
It seems you do not break the loop when the match is a success. Use this instead :
function checkthis(e:Event)
{
for(var o:int=0;o<= combo.length; o++)
if((combo[o] == truecombo[o]) && (combo.length==truecombo.length)) {
equal=true;
break;
}
if (equal) {
stage.removeEventListener(Event.ENTER_FRAME, checkthis);
endSeq();
}
}
Here's a really simple loop:
var equal:Boolean=true
if(combo.length == truecombo.length) {
for(var i:int=0; i<combo.length; i++) {
if(combo[i] != truecombo[i]) {
equal=false;
break;
}
}
} else {
equal=false;
}
if(equal) {
//do whatever
}
This assumes both are equal, until we find out otherwise. So if the lengths are different, they are not equal. If the ith element is different, they are not equal.
In the end, you check if your flag equal is true and do whatever you want to do.