AS 3 know if only certain characters are inside a string - actionscript-3

with AS3 is there a simple way to understand if a string is composed only with 2 characters? for instance binary number. Can I understand if the string that I am inspecting is composed only of 0 and 1?

Something like the following should do the trick :
private function isBinary(str:String):Boolean
{
var binary:Boolean = true;
for (var i:int = 0; i < str.length; i++)
{
if (str.charAt(i) != "0" && str.charAt(i) != "1")
{
binary = false;
break;
}
}
return binary;
}

Related

Get unique random numbers from 1-40

I want to get unique random numbers each time from nos 1-40 without using an array.Is there any optimised way to get this in action script 3.
No, you have to use permutation, as you have to record those numbers you've already generated. And using these numbers require a set of some kind, aka Array. It's possible to solve this issue by using other data types, but they will essentially narrow down to an array of some sort.
A simple permutation code looks like this:
class Permutation {
private var _a:Array; // or Vector.<int> if you like
private var n:int; // next element
public function Permutation() {
reset(1);
}
public function reset(size:int=100):void {
_a.length=0;
for (n=0;n<size;n++) _a.push(n);
for (n=0;n<size;n++) {
var x:int=Math.floor(size*Math.random());
if (x==n) continue;
var swap:int=_a[x];
_a[x]=_a[n];
_a[n]=swap;
}
n=0;
}
public function getNext():int {
if (n==_a.length) return -1; // or any error value
n++;
return _a[n-1];
}
}
No array.
var generatedNumberCount:int;
var generatedNumberRef:Object = {};
for(var i:int = 0; i < 150; i++)
{
var result:Number = generateRandomInt(50);
trace(result);
}
trace(generatedNumberCount)
function generateRandomInt(limit:int):Number
{
if(generatedNumberCount >= limit)
{
return NaN;
}
var output:int = Math.ceil(Math.random() * limit);
while(generatedNumberRef[output] != undefined)
{
output = Math.ceil(Math.random() * limit);
}
generatedNumberRef[output] = true;
generatedNumberCount++;
return output;
}

Issue with for loop in an Array

Initially the array holds the default values as 100. Once if the enemy looses its health then i want to set the default values from 100 to 0. When all the array elements gets a value of 0 then the message will trace as game win.
var enemyHealth:Array = new Array(100,100,100,100,0);
for (var i = 0; i< enemyHealth.length; i++)
{
if (enemyHealth[i] == 0)
{
trace ("game win");
}
}
Actually the issue is if any one of the array element holds a value of 0 then it trace a massage as game win.
So can any one help me in this regard.
You need to check all elements, not just one:
var allZero:Boolean = true;
var enemyHealth:Array = new Array(100,100,100,100,0);
for (var i = 0; i< enemyHealth.length; i++)
{
if (enemyHealth[i] != 0)
{
allZero = false;
break; // We know it's not a win, so we can stop the loop early
}
}
if (allZero) {
trace ("game win");
}
I would do something like this
var enemyHealth:Array = new Array(100,100,100,100,0);
var isDead:Boolean = true;
for (var i = 0; i< enemyHealth.length; i++)
{
if (enemyHealth[i] != 0)
{
isDead = false;
break;
}
}
if(isDead)
{
trace ("Game Win");
}
You can do what the other answerers have said or something like this which might help you more to get the exact amount of enemies dead.
var enemyHealth:Array = new Array(100,100,100,100,0);
var enemiesDead:int=0;
for (var i = 0; i< enemyHealth.length; i++)
{
if (enemyHealth[i] == 0)
{
enemiesDead++;
}
}
if(enemiesDead==enemyHealth.length)
{
trace("Game Over");
}
You can use the every method to check that every element of your array (or vector) meet a criterion.
const enemyHealth:Vector.<uint> = new <uint>[100,100,100,100,0];
const zeroHealth:Function = function(item:uint, index:int, vector:Vector.<uint>):Boolean {
return item === 0;
}
if (enemyHealth.every(zeroHealth)) {
trace("Game win")
}
I have changed the array to a Vector because they are more efficient, and you can specify the type of the elements, but it also works fine with array.

setting the chances of occurrence of elements in an array

For example I have 3 elements in an array:
public function randomTile():Number
{
var tiles:Array = new Array(fire,ice,water);
var index:Number=Math.floor(Math.random()*tiles.length);
return tiles[index];
}
How to set the chances of occurrence of fire(70%), ice(10%), and water(20%)?
This should work for any number of elements and you can specify any chance value.
var tiles:Array = [
{"item":"fire", "chance":70 },
{"item":"ice", "chance":10 },
{"item":"water","chance":20}
];
var picked:Object = pickRandomByChance(tiles);
trace(picked.item);
public function pickRandomByChance(options:Array):Object
{
var copy:Array = [];
var range:Number = 0;
for (var i:int = 0; i < options.length; i++)
{
copy.push( { "item":options[i].item, "chance":options[i].chance } );
range += copy[i].chance;
if (i > 0)
copy[i].chance += copy[i - 1].chance;
}
var pick:Number = Math.floor(Math.random() * range);
for (i = 0; i < copy.length; i++)
{
if (pick <= copy[i].chance)
return copy[i];
}
return null;
}
There quite a few ways you could do this, and it largely depends of the scope of your project. If you just have the three elements, using a switch statement would be easy:
var rand:Number = Math.random();
switch(true){
case rand >= .3:
//use fire
break;
case rand >= .1
//use water
break;
default:
//use ice
}
Someone else may have a better way though

XMLListCollection find index value

I want to find specific value on a XMLListCollection.
I try to use something like this but it doesn't work!
var xmllisteRDV:XMLList= XML(event.result).RDVClinik;
xmlCollSuivi = new XMLListCollection(xmllisteRDV);
var index:Number = -1;
for(var i:Number = 0; i < xmllisteRDV.length(); i++)
{
if(XML(xmllisteRDV[i]).#grDateDeb == todayDate)
{
index = i;
break;
}
}
First going to try pointing out errors in the original code:
var xmllisteRDV:XMLList= XML(event.result).RDVClinik; //Unnecessary cast, event.result is Object compiler will not check or know the run-time type, doesn't care because Object is declared dynamic meaning properties can be added to it dynamically, if RDVClinik didn't exist on the particular Object type it would simply be null casting as XML gives it no information about this "property"
xmlCollSuivi = new XMLListCollection(xmllisteRDV);
var index:Number = -1;
for(var i:Number = 0; i < xmllisteRDV.length(); i++) //length is a property not a method on XMLListCollection this should throw a compile time error
{
if(XML(xmllisteRDV[i]).#grDateDeb == todayDate)// I see no type when debugging for the result of xmllisteRDV[i] not positive here but this cast is at the least unnecessary
{
index = i;
break;
}
}
Here's a version I think will work possibly with changes to how todayDate is built
var date:Date = new Date();
var todayDate:String = date.dateUTC+"/"+date.dayUTC+"/"+date.fullYear;
var index:int=-1;
for(var i:int = 0; i < flex3Projects.length; i++)
{
trace(xmllisteRDV[i].#grDateDeb)
if(xmllisteRDV[i].#grDateDeb.toString() == todayDate)
{
index = i;
break;
}
}
With you help, I found the solution
private function setSelectedItem():void
{
var gData:Object = dgSuiviClini.dataProvider;
var todayDate:String= new DateUtility().DateAsToString(new Date());
for(var i:Number=0; i < gData.length; i++)
{
var thisObj:Object = gData.getItemAt(i);
if(thisObj.grDateDeb == todayDate)
{
dgSuiviClini.selectedIndex = i;
//sometimes scrollToIndex doesnt work if validateNow() not done
dgSuiviClini.validateNow();
//dgSuiviClini.scrollToIndex(i);
}
else{
dgSuiviClini.validateNow();
// dgSuiviClini.scrollToIndex(gData.length);
}
}
dgSuiviClini.validateNow();
dgSuiviClini.editedItemPosition = { rowIndex: gData.length-1, columnIndex: nColSaisie };
}
Thanks

Returns and/or breaks in the middle of a loop. Is it ever acceptable?

Suppose we have an array of integers. We've written a function to fetch the index of the first specified value in the array, or -1 if the array does not contain the value..
So for example, if the array = { 4, 5, 4, 4, 7 }, then getFirstIndexOf(4) would return 0, getFirstIndexOf(7) would return 4, and getFirstIndexOf(8) would return -1.
Below, I have presented three different ways to write this function. It is a widely accepted coding standard that returns in the middle of functions, and breaks in the middle of loops are poor practice. It seems to me that this might be an acceptable use for them.
public int getFirstIndexOf(int specifiedNumber) {
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
return i;
}
}
return -1;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
result = i;
break;
}
}
return result;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber && result == -1) {
result = i;
}
}
return result;
}
What do you think? Which is best? Why? Is there perhaps another way to do this?
I think it's poor practice to run a full loop when you have already found your result...
If you really want to avoid using return from the middle of the loop, I would sugest to use a "sentinel" to stop your loop.
public int getFirstIndexOf(int specifiedNumber, int[] array) {
boolean found = false;
boolean exit = false;
int i = 0;
int arraySize = array.length();
while(!found && !exit) {
if(array[i] == specifiedNumber) {
found = true;
} else {
if(i++ > arraySize) {
exit = true;
}
}
if(found ==true) {
return i;
} else {
return 99999;
}
}
edit: I hate to indent code using spaces in StackOverflow...
That's why do...while & while loop was invented.
As requested:
public int getFirstIndexOf(int specifiedNumber) {
int i = array.Length;
while(--i > -1 && array[i] != specifiedNumber);
return i;
}