actionscript 2: pick 3 random nummers from array - random

i need 3 random variables from array 0-36 (roulette).
i have this code. script return first 3 nummers from random array.
i need return 3 random nummers (from random position) from random array.
help me please.
onClipEvent (load) {
// field 0-36
var rands = [];
for (var i = 0; i < 36; ++i)
{
rands[i] = i;
}
// random sorting array
rands.sort(function(a,b) {return random(3)-1;});
// final variables 1,2,3
random1 = rands[0];
random2 = rands[1];
random3 = rands[2];
}
this is possible code for 1 variable, i need convert this to 3 variables in AS2
n = 3;
for (var i:Number = 0; i < n; i++) {
var randomSelection = Math.floor((Math.random() * rands.length));
trace("Selected: " + rands[randomSelection]);
}

It's not 100% clear from your question what you want, but this is my guess:
var n = 3;
var random = [];
for (var i:Number = 0; i < n; i++) {
// Store the random selections in an array
random.push(Math.floor(Math.random() * rands.length));
}
// You could assign them to variables or access directly via array
var random1 = random[0];
var random2 = random[1];
var random3 = random[2];

Related

why not pass all test case in problem balanced numbers in codewars?

Currently i am doing a challenge in codewars on Balanced numbers and i wrote the code in dart and it successfully completed 100 test cases but for long numbers it is not working properly...So i think that it need some conditions for this long numbers:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i <= a.length / 2; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
//print(b);
for (var i = 0; i < b.length / 2; i++) {
right_sum += int.parse(b[i]);
}
//print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
link to the challenge:https://www.codewars.com/kata/balanced-number-special-numbers-series-number-1/train/dart
The compiler verdict for the code is wrong answer because of a simple logical error.
This is because the length of the list has not been calculated correctly
Kindly have a look at the corrected code below, which passes all the 110 test on the platform:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
double d = ((a.length-1) / 2);
int len = d.floor();
print(len);
for (var i = 0; i < len; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
print(b);
for (var i = 0; i < len; i++) {
right_sum += int.parse(b[i]);
}
print(left_sum);
print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
Your problem is not about "long numbers" since you code also fails for the test case using the number 13.
You properly did not read the following rules:
If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0
The middle digit(s) should not be considered when determining whether a number is balanced or not, e.g 413023 is a balanced number because the left sum and right sum are both 5.
So you need to test if the number are even or uneven since we need to use that information to know how many digits we should use in the sum on each side.
I have done that in the following implementation:
String balancedNum(int numb) {
final numb1 = numb.toString();
final a = numb1.split("");
var split = (a.length / 2).floor();
if (a.length % 2 == 0) {
split--; // the number is even
}
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i < split; i++) {
print(a[i]);
left_sum += int.parse(a[i]);
}
final b = a.reversed.toList();
for (var i = 0; i < split; i++) {
right_sum += int.parse(b[i]);
}
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}

Hash a Set of Integers from a Domain into a Set of Buckets

Say I have a set of integers ranging between 1-100. I will only have 5 of these integers drawn out of a hat. I want to then take those 5 integers and place them into 5 buckets guaranteed unique (without having to deduplicate or anything using something like quadratic probing). Wondering how to do that.
For example, say I have these numbers (random from 1-100):
1 5 20 50 100
I then want to take those numbers and place them into these 5 buckets:
a b c d e
Using some hash function to accomplish it. For example, perhaps like this:
hash(1) -> b
hash(5) -> a
hash(20) -> e
hash(50) -> d
hash(100) -> c
Wondering how to write the hash function so that it takes a number x from a domain of numbers D and a set of numbers D(X) from that domain, and outputs 1 bucket b from the set of buckets B.
H : D(X) -> B
Next time around I might have 6 numbers between 1 and 1,000, going into 6 buckets. So then I would need a new hash function that works using those constraints (6 numbers, 6 buckets, range 1-1,000).
The goal is as few steps as possible.
Note: The hash function for this example won't take integers in a domain larger than 10,000 lets say, as well as the size of the set of integers limited to some small number too like 1,000.
Update
Basically I am trying to get this to happen:
// var domain = [1, 2, ..., 100]
// var set = [1, 5, 20, 50, 100]
// var buckets = [1, 2, 3, 4, 5]
hash(1) // 2
hash(5) // 1
hash(20) // 5
hash(50) // 4
hash(100) // 3
function hash(integer) {
if (integer == 1) return 2
if (integer == 5) return 1
if (integer == 20) return 5
if (integer == 50) return 4
if (integer == 100) return 3
}
But I don't know how to construct that hash function dynamically.
One solution (in JavaScript) would be to just create a map like this:
var map = {
1: 2,
5: 1,
20: 5,
50: 4,
100: 3
}
But that's sort of cheating because the object in JavaScript is implemented as a hashtable underneath (or something like that). So I am looking for how to do this at a low level, just using basically what assembly gives you.
Pretty much, I want to do this:
1
5 |
| | 20
| | 50 |
| | 100 | |
[ slot1, slot2, slot3, slot4, slot5 ]
Where 1 is somehow "hashed" to go into that slot2 in an array of size 5 (that slot is arbitrary for this example), etc.
Suppose the domain of your integer values is the range from 0 to n-1, and you want the set of values [x0, x1, ..., xk-1] to map to values from 0 to k-1.
Create an array of n values containing the numbers from 0 to k-1 in roughly equal amounts, for example [a0 = 0, a1 = 1, ..., ak = 0, ..., an = n%k].
Then for each of the k values in the initial set (xi, where i = 0 .. k-1), change the k-th element of this array to i, either by direct assignment or by swapping with a value from elsewhere (taking care not to clobber a value set for a previous element of the initial set).
Then to hash a value y, just fetch the y-th value from this array.
DEMO
Here's a Javascript demo that basically implements the above algorithm, except that instead of pre-filling the array with values from 0 to k-1, it first inserts the hash values for the selected items, then fills the remaining items with the repeating sequence of numbers from 0 to k-1. You will probably get better collision resistance by using a random sequence instead of incrementing values, but I hope you get the picture.
var hash_array;
function generate_hash() {
var i, j, k;
var v = document.getElementById;
var n = document.getElementById("n").value;
// Create a new hash lookup table
hash_array = Array(n);
// Initialize every value to -1
for (i=0; i<n; i++) hash_array[i] = -1;
// Map the given values to the first k hash buckets
var initial_values = document.getElementById("init").value.split(/ +/);
k = initial_values.length;
for (i=0; i<k; i++) {
hash_array[initial_values[i]] = i;
}
// Fill the remaining buckets with values from 0 to k-1
// This could be done by selecting values randomly, but
// here we're just cycling through the values from 0 to k-1
for (i=j=0; i<hash_array.length; i++) {
if (hash_array[i] == -1) {
hash_array[i] = j;
j = (j + 1) % k;
}
}
document.getElementById("gen").innerHTML = "Hash lookup table:<br>" + hash_array.join(", ");
}
<h2>Demo</h2>
<p>Creating a hash function that works on integer values less than <i>n</i>. What is the value of <i>n</i>?<br>
<input type="number" id="n" min="6" max="100" value="20"/></p>
<p>Enter a few different values separated by spaces. These will hash to the first buckets<br/>
<input type="text" size="40" id="init" value="2 3 5 6 9"/></p>
<p id="gen"><button onclick="generate_hash(); return false">Generate hash table</button></p>
Something like this should work:
Create a set of bucket IDs and populate it ahead of hashing (assumption here is that set guarantees uniqueness). This means that you have to know in advance how many buckets you want.
For each element from the input set calculate hash(element) modulo bucketIds.size to find index of the next ID to use.
Remove the resulting bucket ID from the set of bucked IDs
Repeat (until you are done or the set of IDs is exhausted)
Feel free to inspect the noddy implementation in JS using arrays (Node8).
If you'd like a function that's not a straight map, you could also experiment with Polynomial Regression.
Here's a JavaScript example using some free code under the GNU license.
/***************************************************************************
* Copyright (C) 2018 by Paul Lutus *
* lutusp#arachnoid.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
// classic Gauss-Jordan matrix manipulation functions
var gj = gj || {}
gj.divide = function(A, i, j, m) {
for (var q = j + 1; q < m; q++) {
A[i][q] /= A[i][j];
}
A[i][j] = 1;
}
gj.eliminate = function(A, i, j, n, m) {
for (var k = 0; k < n; k++) {
if (k != i && A[k][j] != 0) {
for (var q = j + 1; q < m; q++) {
A[k][q] -= A[k][j] * A[i][q];
}
A[k][j] = 0;
}
}
}
gj.echelonize = function(A) {
var n = A.length;
var m = A[0].length;
var i = 0;
var j = 0;
var k;
var swap;
while (i < n && j < m) {
//look for non-zero entries in col j at or below row i
k = i;
while (k < n && A[k][j] == 0) {
k++;
}
// if an entry is found at row k
if (k < n) {
// if k is not i, then swap row i with row k
if (k != i) {
swap = A[i];
A[i] = A[k];
A[k] = swap;
}
// if A[i][j] is != 1, divide row i by A[i][j]
if (A[i][j] != 1) {
gj.divide(A, i, j, m);
}
// eliminate all other non-zero entries
gj.eliminate(A, i, j, n, m);
i++;
}
j++;
}
}
// a simple data class
function Pair(x,y) {
this.x = x;
this.y = y;
};
Pair.prototype.toString = function() {return x + ',' + y};
// matrix functions
var matf = matf || {}
// a weak substitue for printf()
matf.number_format = function(n,p,w) {
s = n.toExponential(p);
while(s.length < w) {
s = ' ' + s;
}
return s;
}
// produce a single y result for a given x
matf.regress = function(x, terms) {
var y = 0;
var m = 1;
for (var i = 0; i < terms.length;i++) {
y += terms[i] * m;
m *= x;
}
return y;
}
// compute correlation coefficient
matf.corr_coeff = function(data, terms) {
var r = 0;
var n = data.length;
var sx = 0;
var sx2 = 0, sy = 0, sy2 = 0, sxy = 0;
var x, y;
for (var i = 0;i < data.length;i++) {
pr = data[i];
var x = matf.regress(pr.x, terms);
var y = pr.y;
sx += x;
sy += y;
sxy += x * y;
sx2 += x * x;
sy2 += y * y;
}
var div = Math.sqrt((sx2 - (sx * sx) / n) * (sy2 - (sy * sy) / n));
if (div != 0) {
r = Math.pow((sxy - (sx * sy) / n) / div, 2);
}
return r;
}
// compute standard error
matf.std_error = function(data, terms) {
var r = 0;
var n = data.length;
if (n > 2) {
var a = 0;
for (var i = 0;i < data.length;i++) {
pr = data[i];
a += Math.pow((matf.regress(pr.x, terms) - pr.y), 2);
}
r = Math.sqrt(a / (n - 2));
}
return r;
}
// create regression coefficients
// for provided data set
// data = pair array
// p = polynomial degree
matf.compute_coefficients = function(data, p) {
p += 1;
var n = data.length;
var r, c;
var rs = 2 * p - 1;
//
// by request: read each datum only once
// not the most efficient processing method
// but required if the data set is huge
//
// create square matrix with added RH column
m = Array();
for (var i = 0; i < p; i++) {
mm = Array();
for (var j = 0; j <= p; j++) {
mm[j] = 0;
}
m[i] = mm;
}
//double[][] m = new double[p][p + 1];
// create array of precalculated matrix data
mpc = Array();
for(var i = 0;i < rs;i++) {
mpc[i] = 0;
}
mpc[0] = n;
for (var i = 0;i < data.length;i++) {
pr = data[i];
// process precalculation array
for (r = 1; r < rs; r++) {
mpc[r] += Math.pow(pr.x, r);
}
// process RH column cells
m[0][p] += pr.y;
for (r = 1; r < p; r++) {
m[r][p] += Math.pow(pr.x, r) * pr.y;
}
}
// populate square matrix section
for (r = 0; r < p; r++) {
for (c = 0; c < p; c++) {
m[r][c] = mpc[r + c];
}
}
// reduce matrix
gj.echelonize(m);
// extract result column
terms = Array();
for (var i = 0;i < m.length;i++) {
mc = m[i];
terms[i] = mc[p];
}
return terms;
}
// test the system using known data
matf.test = function() {
var xd = [-1,0,1,2,3,5,7,9];
var yd = [-1,3,2.5,5,4,2,5,4];
data = Array();
for(var i = 0;i < xd.length;i++) {
data[i] = new Pair(xd[i],yd[i]);
}
terms = compute_coefficients(data,6);
var prec = 16;
var width = 24;
for(var i = 0;i < terms.length;i++) {
print(number_format(terms[i],prec,width) + ' * x^' + i);
}
cc = corr_coeff(data,terms);
print ('cc = ' + number_format(cc,prec,width));
se = std_error(data,terms);
print('se = ' + number_format(se,prec,width));
}
//test();
// "data" is an array of Pair(x,y) data
// p = polynomial degree
matf.process_data = function(data,p) {
var terms = matf.compute_coefficients(data,p);
var cc = matf.corr_coeff(data,terms);
var se = matf.std_error(data,terms);
return [terms,cc,se];
}
/**** END Paul Lutus' code ****/
function f(cs, x){
let n = cs.length - 1;
let result = 0;
for (let i=0; i<cs.length; i++)
result += cs[i] * Math.pow(x, i);
return result;
}
var data = [[1,1], [5,2], [20,3], [50,4], [100,5]];
var xy_data = []
for (let i of data)
xy_data.push(new Pair(i[0], i[1]));
var result = matf.process_data(xy_data, xy_data.length - 1);
for (let i=0; i<data.length; i++)
console.log(data[i][0], f(result[0], data[i][0]));

Create Random Number List With No Repetition

I'm looking to create a list of 'random' numbers from 1 to 15 but without any repetition. I have created an array and looking to store each number in it but can't figure out how to do this. I've gotten as far as creating the random list and storing them in the array but can't quite get to ensure there are no repetitions. Any help would be appreciated. My code is as follows:
int[] myList = new int[15];
Random random = new Random();
for (int i = 0; myList.Length; i++)
{
myList[i] = random.Next(1, 15);
}
Because the size of your list is equal to the possible values, you can just create the list in normal order:
int[] myList = new int[15];
for (int i = 0; i < myList.Length; i++)
{
myList[i] = i + 1;
}
and then shuffle it, for example by assigning a random value to each entry and sort by that value:
Random random = new Random();
myList = myList.OrderBy(a => random.Next()).ToArray();
You can do it using Fisher–Yates shuffle.
Sample Implementation:
int n = 15;
int[] myList = new int[n];
Random random = new Random();
for (int i = 0; i < n; i++)
{
myList[i] = i + 1;
}
for (int i = n - 1; i >= 1; i--)
{
int j = random.Next(1, i);
int temp=myList[i];
myList[i]=myList[j];
myList[j]=temp;
}
You need to get the algorithm right.
Start from i=15
Pick a random number from 1 to i.
Append it to the list.
Swap it with (i-1)th index.
Decrement i by 1.
Repeat the above steps.
The code for above can be:
int[] myList = new int[15];
int[] original_list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
Random random = new Random();
for (int i = myList.Length; i>=0; i--)
{int randNo = random.Next(0, i-1);
myList[i] = original_list[randNo];
swap(original_list[i-1],original_list[randNo]); //your swap method
}

How to find number of times a number repeated in pascal's triangle?

Can anyone give an algorithm to find the number of times a number repeats in pascal's triangle? For example
num - No of times
1 - infinite
2 - 1
3 - 2
4 - 2
. .
6 - 3
. .
10 - 4
. .
for image Link
Or in other way, how many nCr 's are possible for nCr = x , where x is any given integer?
Just count. You know n > 1 can only appear in the first n+1 rows of Pascal's triangle. And that each row is symmetric, and increasing (for the first half). That saves time.
See http://oeis.org/A003016 for more about the sequence
I had to write something similar for a hackathon challenge. This code will find all the numbers 1 to MAX_NUMBER_TO_SEARCH that have a count of more than MINIMUM_COUNT in the Pascal Triangle of size PASC_SIZE. You can obviously alter it to only count for a single number. Not super efficient obviously.
function pasc(n) {
var xx = [];
var d = 0;
var result = [];
result[0] = [1];
result[1] = [1, 1];
for (var row = 2; row < n; row++) {
result[row] = [1];
for (var col = 1; col <= row - 1; col++) {
result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
result[row].push(1);
}
for (var ff = 0; ff < result[row].length; ff++) {
xx[d++] = (result[row][ff]);
}
}
return xx;
}
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
var MAX_NUMBER_TO_SEARCH = 5000;
var MINIMUM_COUNT = 5;
var PASC_SIZE = 1000;
var dataset = pasc(PASC_SIZE);
for (var i = 0; i < MAX_NUMBER_TO_SEARCH; i++) {
if (countInArray(dataset, i) >= MINIMUM_COUNT) {
console.log(i + " Count:" + countInArray(dataset, i) + "\n");
}
}

modifying the lengthY of some cubes is slow

I want to write a 3d version of a fft. (Like this:https://wiki.mozilla.org/File:Fft.png)
So I created a few bars and in an outside function, my first aproach was to set the lengthY to a value. Then I call bar.modified() to force it to be repainted.
If I now use more than 50 bars, it is horrible slow (on my 4 core CPU). I guess there's a better way to do it, right?
Source:
var elements = new Array();
create3d = function(len) {
var r = new X.renderer3D();
r.init();
if(a.length == 0){
for ( var y = 0; y < len; y++) {
var c = new X.cube();
a.push(c);
}
}
for ( var i = 0; i < len; i++) {
a[i].center = [i*2 , 0, 0];
a[i].lengthX = 1;
a[i].lengthY = 20;
a[i].lengthZ = 1;
a[i].color = [i%2,0,0];
r.add(a[i]);
}
r.render();
};
function setVal(index,val){
var element = a[index];
element.lengthY = val;
element.modified();
}
I created a JSFiddle on how to do that and it is pretty fast for 1000 cubes
http://jsfiddle.net/haehn/6fVRC/

Resources