Actionscript randomly distribute objects on stage - actionscript

I'm trying to distribute 3 objects randomly on my stage but it's not working. My movie is 800x800.
function makeRock():void{
var tempRock:MovieClip;
for(var i:Number = 1; i < 3; i++){
tempRock = new Rock();
tempRock.x = Math.round(800);
tempRock.y = Math.round(-800);
addChild(tempRock);
}
}
What am I doing wrong?

Replace Math.round(800); with Math.random()*800;
function makeRock():void
{
var tempRock:MovieClip;
var i:uint = 0;
for(i; i < 3; i++)
{
tempRock = new Rock();
tempRock.x = Math.random()*800;
tempRock.y = Math.random()*800;
addChild(tempRock);
}
}
Math.round(800) is just returning 800.
Math.random() returns a random number between 0 and 1, which you can multiply by 800 to get a random result of 0-800. A good note to make is that Math.random() never actually returns 1.0. Just everything from 0 up to 1.
Further reading:
As a side note: this makes it simple to return a random element from an array; because you're never getting 1 you can cast the result of Math.random()*array.length to uint() and always be within the boundaries of the array length.
eg.
var ar:Array = [1,2,"hello",4,5,6,7,8,9,0];
var randomElement:Object = ar[uint(Math.random()*ar.length)];
trace(randomElement);

Related

How can I ask the user of any program for a value in Swift?

In JS it is called "prompt", but it is obviously not the same keyword in Swift. So my problem actually is that I want to ask the user of any program for a value. So how do I ask him and how do I safe that answer into a variable?
So this is how I would write it in Javascript for example when I want to use the input as a value for my calculations:
var n1 = prompt("give me a value");
var n2 = 3;
var i = 0;
var sum = 0;
while(i < n1){
sum = sum + n2;
i += 1;
}
document.write(sum)
And now I don't really know how to write the same in swift. I just want to ask the user for a value in "n1".
var n1 = 9;
var n2 = 5;
var i = 0;
var sum = 0;
while(i < n1){
sum = sum + n2;
i += 1;
}
print(sum)
How shall I write this in "var n1" ?
You can do it in Command Line Tool.
Create New project - mac os tab - Command Line Tools.
You can ask user for input using readLine().
let a = readLine()
if let input = a {
print(input)
}

flutter how to generate random numbers without duplication

Is there any way to generate random numbers without duplication?
For instance I want to generate 50 random numbers from 1 to 100 no duplication, any way to do this or do I have to check every time incoming number is already created or not?
you can use shuffle as following code.
import 'dart:math';
var list = new List<int>.generate(10, (int index) => index); // [0, 1, 4]
list.shuffle();
print(list);
You can use Set. Each object can occur only once when using it. Just try this:
Set<int> setOfInts = Set();
while (setOfInts.length < 50) {
setOfInts.add(Random().nextInt(range) + 1);
}
You can read the documentation here: Set Doc
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.
import 'dart:math';
class RandomList {
static final _random = new Random();
static List<int> uniqueSample({int limit, int n}) {
final List<int> sortedResult = [];
final List<int> result = [];
for (int i = 0; i < n; i++) {
int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time
// Increment the number so that it picks from the remaining list of available numbers
int j = 0;
for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;
sortedResult.insert(j, rn);
result.add(rn);
}
return result;
}
}
I haven't tested it exhaustively but it seems to work.

Zapier Javascript Issue

Zapier splits out my JSON arrays to two separate variables when it runs in a code action, any idea why? If I include the array in the code action, it works - but if I pull it from another step it splits it out.
Code:
var jsonOrg = JSON.parse(inputData.data);
var orgList = inputData.origin;
var orgArray = orgList.split(",");
var out =[];
for (var i = 0; i<jsonOrg.rows.length; i++){
for (var j = 0; j<orgArray.length; j++){
if (jsonOrg.rows[i].product === orgArray[j]){
out += jsonOrg.rows.id[i] + ",";
}
}
}
output = [{id: 123, hello:out }];

Actionscript: compare variables from an array

Need Help, I have totalA - totalB - totalC - totalD, need to select the highest variable from this 4 but if the highest one equal an other one, must show which variables equals.
I have used this code but when it meets the equals ( A = B = C ) it dispalys just D
var aNumber:Array = new Array(totalA , totalB , totalC , totalD );
for(var i:Number = 0; i < aNumber.length; i++)
{
if(aNumber[i] < aNumber[i+1])
{
bigger = aNumber[i+1];
}
}
If you're wanting to output a letter/etc for the scores, I'd use an object/dictionary rather than a straight array.
Basically, the algorithm would be:
Capture the scores in an object/dictionary, where the key is the name of the player and the value is their score.
Enumerate each item/player in the object/dictionary and compare the current score to the maximum score.
If the current score is greater than the maximum score, clear all previous winners, set the new maximum score and add the current player to the winners.
If the current score is equal to the maximum score, add the current player to the winners array.
Following is some hastily concocted actionscript.
var scores:Object = {
'A': totalA,
'B': totalB,
'C': totalC,
'D': totalD
};
var maxScore:Number = -1;
var winners:Array = new Array();
for(var player:String in scores)
{
var score:Number = scores[player];
if (score > maxScore)
{
maxScore = score;
winners = new Array();
winners.push(player);
}
else if (score == maxScore)
{
winners.push(player);
}
}
At the end of this segment of code, you should have the highest score in maxScore and the names of the winning players in the winners array.
var aNumber:Array = new Array(totalA , totalB , totalC , totalD );
bigger = aNumber[0];
for(var i:Number = 1, var j:Number = (aNumber.length)-1; i<j ; i++)
{
if(bigger < aNumber[i])
{
bigger = aNumber[i];
}
}
var highest:Array = new Array();
highest[] = bigger;
for(var i:Number = 0, var j:Number = (aNumber.length); i<j ; i++){
if(aNumber[i] == bigger){
highest[] = aNumber[i];
}
}
Array highest will now hold the highest score(s)
This solution can be a bit more elegant (assuming that a array contains integer values):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.controls.Alert;
private var array:Array = [1,2,3,4,3];
public function init():void{
var maxValue:Number = getMaxValue(new ArrayCollection(array));
Alert.show(String(maxValue)); //show value 4
}
private function getMaxValue(tempArr:ArrayCollection):Number {
var dataSort:Sort = new Sort();
dataSort.fields = [new SortField(null,false,true,true)];;
tempArr.sort = dataSort;
tempArr.refresh();
return tempArr[0];
}
]]>
</mx:Script>
</mx:Application>
According to this example, I order the array from highest to lowest and take the first. Its works perfectly. I hope this helps

Hash of a cell text in Google Spreadsheet

How can I compute a MD5 or SHA1 hash of text in a specific cell and set it to another cell in Google Spreadsheet?
Is there a formula like =ComputeMD5(A1) or =ComputeSHA1(A1)?
Or is it possible to write custom formula for this? How?
Open Tools > Script Editor then paste the following code:
function MD5 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
Save the script after that and then use the MD5() function in your spreadsheet while referencing a cell.
This script is based on Utilities.computeDigest() function.
Thanks to gabhubert for the code.
This is the SHA1 version of that code (very simple change)
function GetSHA1(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, input);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
Ok, got it,
Need to create custom function as explained in
http://code.google.com/googleapps/appsscript/articles/custom_function.html
And then use the apis as explained in
http://code.google.com/googleapps/appsscript/service_utilities.html
I need to handtype the complete function name so that I can see the result in the cell.
Following is the sample of the code that gave base 64 encoded hash of the text
function getBase64EncodedMD5(text)
{
return Utilities.base64Encode( Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, text));
}
The difference between this solution and the others is:
It fixes an issue some of the above solution have with offsetting the output of Utilities.computeDigest (it offsets by 128 instead of 256)
It fixes an issue that causes some other solutions to produce the same hash for different inputs by calling JSON.stringify() on input before passing it to Utilities.computeDigest()
function MD5(input) {
var result = "";
var byteArray = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(input));
for (i=0; i < byteArray.length; i++) {
result += (byteArray[i] + 128).toString(16) + "-";
}
result = result.substring(result, result.length - 1); // remove trailing dash
return result;
}
to get hashes for a range of cells, add this next to gabhubert's function:
function RangeGetMD5Hash(input) {
if (input.map) { // Test whether input is an array.
return input.map(GetMD5Hash); // Recurse over array if so.
} else {
return GetMD5Hash(input)
}
}
and use it in cell this way:
=RangeGetMD5Hash(A5:X25)
It returns range of same dimensions as source one, values will spread down and right from cell with formulae.
It's universal single-value-function to range-func conversion method (ref), and it's way faster than separate formuleas for each cell; in this form, it also works for single cell, so maybe it's worth to rewrite source function this way.
Based on #gabhubert but using array operations to get the hexadecimal representation
function sha(str){
return Utilities
.computeDigest(Utilities.DigestAlgorithm.SHA_1, str) // string to digested array of integers
.map(function(val) {return val<0? val+256 : val}) // correct the offset
.map(function(val) {return ("00" + val.toString(16)).slice(-2)}) // add padding and enconde
.join(''); // join in a single string
}
Using #gabhubert answer, you could do this, if you want to get the results from a whole row. From the script editor.
function GetMD5Hash(value) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, value);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
function straightToText() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var r = 1;
var n_rows = 9999;
var n_cols = 1;
var column = 1;
var sheet = ss[0].getRange(r, column, n_rows, ncols).getValues(); // get first sheet, a1:a9999
var results = [];
for (var i = 0; i < sheet.length; i++) {
var hashmd5= GetMD5Hash(sheet[i][0]);
results.push(hashmd5);
}
var dest_col = 3;
for (var j = 0; j < results.length; j++) {
var row = j+1;
ss[0].getRange(row, dest_col).setValue(results[j]); // write output to c1:c9999 as text
}
}
And then, from the Run menu, just run the function straightToText() so you can get your result, and elude the too many calls to a function error.
I was looking for an option that would provide a shorter result. What do you think about this? It only returns 4 characters. The unfortunate part is that it uses i's and o's which can be confused for L's and 0's respectively; with the right font and in caps it wouldn't matter much.
function getShortMD5Hash(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (j = 0; j < 16; j += 8) {
hashVal = (rawHash[j] + rawHash[j+1] + rawHash[j+2] + rawHash[j+3]) ^ (rawHash[j+4] + rawHash[j+5] + rawHash[j+6] + rawHash[j+7])
if (hashVal < 0)
hashVal += 1024;
if (hashVal.toString(36).length == 1)
txtHash += "0";
txtHash += hashVal.toString(36);
}
return txtHash.toUpperCase();
}
I needed to get a hash across a range of cells, so I run it like this:
function RangeSHA256(input)
{
return Array.isArray(input) ?
input.map(row => row.map(cell => SHA256(cell))) :
SHA256(input);
}

Resources