Random string in AS3 - string

I have recently worked on AS3 project with a module that works like this:
I have 50 strings and I am picking one randomly of them at a given time. When I am done with the picked one I choose another one of the 49 left again randomly and so on.
I managed to solve this problem using helper arrays, for cycles, mapping index numbers with the strings. Although every thing works just fine I found my code very messed and hard to understand.
Is there a much more easy and cleaner way to solve this problem in AS3?
Maybe there is a library for getting random string out of strings?

Something simple like this class:
public class StringList
{
private var _items:Array = [];
public function StringList(items:Array)
{
_items = items.slice();
}
public function get random():String
{
var index:int = Math.random() * _items.length;
return _items.splice(index, 1);
}
public function get remaining():int{ return _items.length; }
}
And its usage:
var list:StringList = new StringList(['a', 'b', 'c', 'd']);
while(list.remaining > 0)
{
trace(list.random);
}

I'm not sure what do you want to do with that procedure, but here's one proposal:
var stringArray:Array = new Array("string1", "string2", "string2"); //your array with strings
var xlen:uint = stringArray.length-1; //we get number of iterations
for (var x:int = xlen; x >= 0; x--){ //we iterate backwards
var randomKey:Number = Math.floor(Math.random()*stringArray.length); //gives you whole numbers from 0 to (number of items in array - 1)
stringArray.splice(randomKey,1); //remove item from array with randomKey index key
var str:String = stringArray[randomKey]; //output item into new string variable or do whatever
}

Related

Why is AutoMapper enumerating an IEnumerable multiple times?

We ran in to performance issues and tracked it down to AutoMapper enumerating twice over an IEnumerable.
It's easily fixable on our side by simply feeding AutoMapper a List or Array, but I'm still curious if this is expected behavior.
The following minimal repro test fails::
[Test]
public void AutoMapper_Should_Not_Enumerate_Multiple_Times()
{
var counter = 0;
var values = Enumerable.Range(0, 3).Select(_ => counter++);
var mapper = new Mapper(new MapperConfiguration(_ => { }));
var dest= mapper.Map<int[]>(values);
Assert.Equal(3, counter);
}
Result: Counter = 6, dest = [3,4,5], which means the IEnumerable is iterated twice and the second iteration is returned.
I tried debugging this in AutoMapper, but I only figured out that something was first calling Count() and then iterating:
Is this expected behavior? How or where is an IEnumerable mapped to an Array and why is Count() called before iterating?
This is implemented by the ArrayMapper and the implementation is functionally this:
var count = source.Count();
var array = new TDestination[count];
int i = 0;
foreach (var item in source)
array[i++] = newItemFunc(item, context);
return array;

Using objects as Map keys in Haxe

I'm trying to make a Map with an object as a key. The problem is, that when I try to get elements from this map, I always get null. It's because I'm not providing the exact same reference as the key was. I'm providing an object with the same values, so the reference is different.
Is there any way to solve that? Can I make it use some kind of equals() function?
class PointInt
{
public var x:Int;
public var y:Int;
...
}
var map = new Map<PointInt, Hex>();
var a = new PointInt(1, 1);
var b = new PointInt(1, 1);
var hex_a = new Hex();
map[a] = hex_a;
var hex_b = map[b];
/// hex_b == null now because reference(a) == reference(b)
As explained here and here, Map in Haxe works using the reference of the object as the key.
What you want to use instead is a HashMap like this (try.haxe link):
import haxe.ds.HashMap;
class Test {
static function main() {
var map = new HashMap();
map.set(new PointInt(1, 1), 1);
trace(map.get(new PointInt(1,1)));
}
}
class PointInt
{
public var x:Int;
public var y:Int;
public function new(x:Int, y:Int)
{
this.x = x;
this.y = y;
}
public function hashCode():Int
{
return x + 1000*y; //of course don't use this, but a real hashing function
}
public function toString()
{
return '($x,$y)';
}
}
What you need to change in your code, besides using haxe.ds.HashMap instead of Map is to implement a hashCode : Void->Int function in your key object
Since you're using an object that has 2 ints, and the hash map is just 1 int, it will happen that 2 PointInt will have the same hash code. To solve this you could create a hash map that uses strings as hashcode but if you can write (or google) a good hash function you will get better performance.

c# string delimiter

I have string value like this:
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
I just need to retrieve role to string array. I wonder if there is the best way to split the string in C# 4.0
string[] arrStrRole = strRole.Split('|').Select .. ??
Basically, I need brandUK, brandUsa, brandAu to string[] arrStrRole.
Thanks.
string[] arrStrRole = strRole.Split('|').Select(r => r.Split(new []{"role="}, StringSplitOptions.None)[1]).ToArray()
results in an string array with three strings:
branduk
brankdusa
brandAu
you can use string[] arrStrRole = strRole.Split('|',','); and this will split according to | and , characters
You can use String.Split in this LINQ query:
var roles = from token in strRole.Split('|')
from part in token.Split(',')
where part.Split('=')[0] == "role"
select part.Split('=')[1];
Note that this is yet prone to error and requires the data always to have this format. I mention it because you've started with Split('|').Select.... You can also use nested loops.
If you need it as String[] you just need to call ToArray:
String[] result = roles.ToArray();
I would go with Regex rather than splitting string. In combination with your intended Select solution, it could look like this:
var roles = Regex.Matches(strRole, #"role=(\w+)")
.Cast<Match>()
.Select(x => x.Groups[1].Value).ToArray();
You could use an extension like this which would allow you to test it easily.
public static string[] ParseRolesIntoList(this string csvGiven)
{
var list = new List<string>();
if (csvGiven == null) return null;
var csv = csvGiven.Split(',');
foreach (var s in csv)
{
if (string.IsNullOrEmpty(s)) continue;
if(!s.StartsWith("role")) continue;
var upperBound = s.IndexOf("|");
if (upperBound <= 0) upperBound = s.Length;
var role = s.Substring(s.IndexOf("=") + 1,
upperBound - s.IndexOf("=") - 1);
list.Add(role);
}
return list.ToArray();
}
Test below found brankdusa typo in your example. Some of the other answers would not deal with brandAu as it matches slightly differently. Try running this test against them if you like
[Test]
public void Should_parse_into_roles()
{
//GIVEN
const string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
//WHEN
var roles = strRole.ParseRolesIntoList();
//THEN
Assert.That(roles.Length, Is.EqualTo(3));
Assert.That(roles[0], Is.EqualTo("branduk"));
Assert.That(roles[1], Is.EqualTo("brankdusa"));
Assert.That(roles[2], Is.EqualTo("brandAu"));
}
This gives an array of the 3 values.
void Main()
{
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
var arrStrRole = strRole.Split('|',',')
.Where(a => a.Split('=')[0] == "role")
.Select(b => b.Split('=')[1]);
arrStrRole.Dump();
}

adding a js method

I have a js function that is named getID which is basically return document.getElementById(id)
I want to make another function, getTag that would return getElementsByTagName.
The part that I can't seem to manage is that I want to be able to call them like this:
getID('myid').getTag('input') => so this would return all the input elements inside the element with the id myid
Thanks!
ps: getTag would also have to work if it's called by it's own, but then it would just return document.getElementsByTagName
UPDATE:
Thanks to all that have replied! Using your suggestions I came up with this, which works well for me:
function getEl(){
return new getElement();
}
function getElement() {
var scope = document;
this.by = function(data){
if (data.id) scope = scope.getElementById(data.id);
if (data.tag) scope = scope.getElementsByTagName(data.tag);
return scope;
}
}
and I use it like this:
var inputs = getEl().by({id:"msg", tag:"input"});
The way to do that is to prototype Object. To do that, you'll need the following piece of code:
Object.prototype.getTag = function(tagName) {
return this.getElementsByTagName(tagName);
}
However, this will expand all objects because what you really need to prototype, an HTMLElement, is very hard to do consistently. All the experts agree that you should never expand the Object prototype. A much better solution would be to create a function that gets the tag name from another argument:
function getTag(tagName, element) {
return (element || document).getElementsByTagName(tagName);
}
// Usage
var oneTag = getTag('input', getID('myid')); // All inputs tags from within the myid element
var twoTag = getTag('input'); // All inputs on the page
This would require that whatever is returned by getID('myid') (an HTML element) exposes a method named getTag(). This is not the case. Browsers implement the DOM specification and expose the methods defined there.
While you technically can enhance native objects with your own methods, it's best not to do it.
What you try to do has been solved rather nicely in JS libraries like jQuery already, I recommend you look at one of them before you invest time in mimicking what they can do. For example, your line of code would become:
$("#myid input")
in jQuery. jQuery happens to be the most widely used JS library around, there are many others.
Basically, you're going to create a single object that contains each of your methods and also stores all data returned by the native functions. It would look something like this (not tested, but you get the idea):
var MyLib = {
getID: function(id) {
var element = document.getElementById(id);
this.length = 1;
this[0] = element;
return this;
},
getTag: function(tag) {
var elements;
if (this.length) {
for (var i = 0; i < this.length; i++) {
var byTag = this[i].getElementsByTagName(tag);
for (var j = 0; j < byTag.length; j++) {
elements.push(byTag[j]);
}
}
}
for (var i = 0; i < elements.length; i++) {
this[i] = elements[i];
}
this.length = elements.length;
return this;
}
};
You can then use it like this:
var elements = MyLib.getID('myid').getTag('input');
for (var i = 0; i < elements.length; i++)
console.log(elements[i]); // Do something
The only real problem with this approach (besides it being very tricky and hard to debug) is that you have to treat the result of every method like an array, even if there is only a single result. For example, to get an element by ID, you'd have to do MyLib.getID('myid')[0].
However, note that this has already been done before. I recommend you take a look at jQuery, if only to see how they accomplished this. Your code could be simplified to this:
$("#myid input")
jQuery is more lightweight than you think, and including it on your page will not slow it down. You have nothing to lose by using it.
Just use the DOMElement.prototype property.
You'll get something like this :
function getTag(tagName) {
return document.getElementsByTagName(tagName);
}
DOMElement.prototype.getTag = function(tagName) {
return this.getElementsByTagName(tagName);
}
But you should use jQuery for this.
EDIT: My solution doesn't work on IE, sorry !
You could define it as follows:
var Result = function(el)
{
this.Element = el;
};
Result.prototype.getTag = function(tagName)
{
return this.Element.getElementsByTagName(tagName);
};
var getTag = function(tagName)
{
return document.getElementsByTagName(tagName);
};
var getID = function(id)
{
var el = document.getElementById(id);
return new Result(el);
};
Whereby a call to getID will return an instance of Result, you can then use its Element property to access the HTML element returned. The Result object has a method called getTag which will return all child elements matching that tag from the parent result. We then also define a seperate getTag method which calls the document element's getElementsByTagName.
Still though...JQuery is so much easier... $("#myId input");
Unless this is an academic exercise on how to chain methods in JavaScript (it doesn't seem to be, you simply seem to be learning JavaScript), all you have to do is this:
var elements = document.getElementById("someIdName");
var elementsByTag = elements.getElementsByTagName("someTagName");
for (i=0; i< elementsByTag.length; i++) {
alert('found an element');
}
If you want to define a reusable function all you have to do is this:
function myFunction(idName,tagName) {
var elements = document.getElementById(idName);
var elementsByTag = elements.getElementsByTagName(tagName);
for (i=0; i< elementsByTag.length; i++) {
alert('found a ' + tagName + ' element within element of id ' + idName);
}
}
It's true that if this is all the JavaScript functionality you need on your page, then there is no need to import jQuery.

Help on Removal of Dynamically Created sprites

import flash.display.Sprite;
import flash.net.URLLoader;
var index:int = 0;
var constY = 291;
var constW = 2;
var constH = 40;
hydrogenBtn.label = "Hydrogen";
heliumBtn.label = "Helium";
lithiumBtn.label = "Lithium";
hydrogenBtn.addEventListener (MouseEvent.CLICK, loadHydrogen);
heliumBtn.addEventListener (MouseEvent.CLICK, loadHelium);
lithiumBtn.addEventListener (MouseEvent.CLICK, loadLithium);
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function loadHydrogen (event:Event):void {
myTextLoader.load(new URLRequest("hydrogen.txt"));
}
function loadHelium (event:Event):void {
myTextLoader.load(new URLRequest("helium.txt"));
}
function loadLithium (event:Event):void {
myTextLoader.load(new URLRequest("lithium.txt"));
}
var DataSet:Array = new Array();
var valueRead1:String;
var valueRead2:String;
function onLoaded(event:Event):void {
var rawData:String = event.target.data;
for(var i:int = 0; i<rawData.length; i++){
var commaIndex = rawData.search(",");
valueRead1 = rawData.substr(0,commaIndex);
rawData = rawData.substr(commaIndex+1, rawData.length+1);
DataSet.push(valueRead1);
commaIndex = rawData.search(",");
if(commaIndex == -1) {commaIndex = rawData.length+1;}
valueRead2 = rawData.substr(0,commaIndex);
rawData = rawData.substr(commaIndex+1, rawData.length+1);
DataSet.push(valueRead2);
}
generateMask_Emission(DataSet);
}
function generateMask_Emission(dataArray:Array):void{
var spriteName:String = "Mask"+index;
trace(spriteName);
this[spriteName] = new Sprite();
for (var i:int=0; i<dataArray.length; i+=2){
this[spriteName].graphics.beginFill(0x000000, dataArray[i+1]);
this[spriteName].graphics.drawRect(dataArray[i],constY,constW, constH);
this[spriteName].graphics.endFill();
}
addChild(this[spriteName]);
index++;
}
Hi, I am relatively new to flash and action script as well and I am having a problem getting the sprite to be removed after another is called. I am making emission spectrum's of 3 elements by dynamically generating the mask over a picture on the stage. Everything works perfectly fine with the code I have right now except the sprites stack on top of each other and I end up with bold lines all over my picture instead of a new set of lines each time i press a button.
I have tried using try/catch to remove the sprites and I have also rearranged the entire code from what is seen here to make 3 seperate entities (hoping I could remove them if they were seperate variables) instead of 2 functions that handle the whole process. I have tried everything to the extent of my knowledge (which is pretty minimal # this point) any suggestions?
Thanks ahead of time!
My AS3 knowledge is rather rudimentary right now but I think two things may help you.
You could use removeChild before recreating the Sprite. Alternatively, just reuse the Sprite.
Try to add this[spriteName].graphics.clear(); to reset the sprite and start redrawing.
function generateMask_Emission (dataArray : Array) : void {
var spriteName:String = "Mask"+index;
trace(spriteName);
// Don't recreate if sprite object already created
if (this[spriteName] == null)
{
this[spriteName] = new Sprite();
// Only need to add sprite to display object once
addChild(this[spriteName]);
}
for (var i:int= 0; i < dataArray.length; i+=2)
{
this[spriteName].graphics.clear();
this[spriteName].graphics.beginFill(0x000000, dataArray[i+1]);
this[spriteName].graphics.drawRect(dataArray[i],constY,constW, constH);
this[spriteName].graphics.endFill();
}
index++;
}
Just in case anyone was curious or having a similar problem. Extremely simple fix but here is what I did.
Also should mention that I don't think that the graphics.clear function actually fixed the problem (though I didn't have the sprite being cleared properly before), but I believe the problem lies in the beginning of the onloaded function where 3 of those variables used to be outside of the function.
import flash.display.Sprite;
import flash.net.URLLoader;
import flash.events.Event;
var constY = 291; //this value represets the Y value of the bottom of the background spectrum image
var constW = 2; //this value represents the width of every emission line
var constH = 40; //this value represents the height of every emission line
//Create Button Labels
hydrogenBtn.label = "Hydrogen";
heliumBtn.label = "Helium";
lithiumBtn.label = "Lithium";
//These listen for the buttons to be clicked to begin loading in the data
hydrogenBtn.addEventListener (MouseEvent.CLICK, loadHydrogen);
heliumBtn.addEventListener (MouseEvent.CLICK, loadHelium);
lithiumBtn.addEventListener (MouseEvent.CLICK, loadLithium);
var myTextLoader:URLLoader = new URLLoader();//the object to load in data from external files
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);//triggers the function when the file is loaded
var Mask:Sprite = new Sprite(); //This sprite will hold the information for the spectrum to be put on stage
function loadHydrogen (event:Event):void {
myTextLoader.load(new URLRequest("hydrogen.txt"));//starts loading Hydrogen emisson data
}
function loadHelium (event:Event):void {
myTextLoader.load(new URLRequest("helium.txt"));//starts loading Helium emission data
}
function loadLithium (event:Event):void {
myTextLoader.load(new URLRequest("lithium.txt"));//starts loading Lithium emission data
}
function onLoaded(event:Event):void {//the function that handles the data from the external file
var rawData:String = event.target.data; //create a new string and load in the data from the file
var DataSet:Array = new Array();//the array to load values in to
var valueRead1:String; //subset of array elements (n)
var valueRead2:String; //subset of array elements (n+1)
for(var i:int = 0; i<rawData.length; i++){ //loop through the string and cut up the data # commas
var commaIndex = rawData.search(",");
valueRead1 = rawData.substr(0,commaIndex);
rawData = rawData.substr(commaIndex+1, rawData.length+1);
DataSet.push(valueRead1);
commaIndex = rawData.search(",");
if(commaIndex == -1) {commaIndex = rawData.length+1;}
valueRead2 = rawData.substr(0,commaIndex);
rawData = rawData.substr(commaIndex+1, rawData.length+1);
DataSet.push(valueRead2);
}
generateMask_Emission(DataSet);//call the generateMaskEmission function on new data to fill emission lines
}
//This function loops through an array, setting alternating values as locations and alphas
function generateMask_Emission(dataArray:Array):void{
Mask.graphics.clear(); //Clears the Mask sprite for the next set of values
addChild(Mask); //Adds the blank sprite in order to clear the stage of old sprites
//This loop actually draws out how the sprite should look before it is added
for (var i:int=0; i<dataArray.length; i+=2){
Mask.graphics.beginFill(0x000000, dataArray[i+1]);
Mask.graphics.drawRect(dataArray[i],constY,constW, constH);
Mask.graphics.endFill();
}
addChild(Mask);// actually adds the mask we have created to the stage
}

Resources