Multiply each element from array by every element - arrays

JavaScript
I need to do this with for loop,
I want to multiply each element from array (2 * 5 * 10 * 12)
Example
var arrNum = [2,5,10,12]
var sum = 0
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * // I don't know what to do
Any ideas :) ?
I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}

First of all, you will always get result as 0 because
your starting sum condition is 0 then multiplying it by any number in the array will always give you 0.
Here is what you should do -
var sum = 1
for(var i = 0; i < arrNum.length; i++) {
sum = arrNum[i] * sum;
}

Try something like this:
var total = 1;
for (var i = 0; i < arrNum.length; i++) {
total *= arrNum[i];
}

var result = [2,5,10,12].reduce(function(a,b){return a*b;});
I think your question needs more explaining, I suppose you're in JS environment.
Notice the advanced funtions of ES6; I suggest to get in deep of all these advanced operations.
Please notice that under the hood the operation will be exact a for-loop, but the reduce hides the complexity and leave everything cleaner.

put the first element of the array in sum
then multiply sum * array of i which start at 1 since we put first element in sum and then put the result back in the sum
var arrNum = [2,5,10,12]
var sum = arrNum[0]
for(var i = 1; i < arrNum.length; i++) {
sum = sum * arrNum[i];
}
console.log(sum);

I did something like this
var arrNum = [2,5,10,12]
var sum = 0
var temp = 1
for(var i = 0; i < arrNum.length; i++){
temp *=arrNumbers[i]
if(i== arrNumbers.length-1){
sum = temp
}
}
it works, but var sum is not a real 0 ...

Related

Google Apps Script .setvalues For loop not working

The goal of the loop is to fill each cell over 797 rows across 5 columns A, B, C, D and E with a formula whose cell reference increments by 1.
E.g. Column A rows 6 onwards will have formula "=indirect("'Data Repository'!A3++")"
Column B rows 6 onwards will have formula "=indirect("'Data Repository'!B3++")"
What happens when I run the function however is it only fills in column A. I've checked the execution transcript and execution succeeded is logged after the first column has been filled up. I've tried various variations to no avail.
Below is the last variation I've tested:
function indirect(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Fleet - Weekly V3");
var formulaArray = [];
var columns = ["A","B","C","D","E"];
var row = 2;
var text = '=indirect(\"\'Data Repository\'!';
var headerRow = 6;
var column;
for(i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(i = 0; i < 797; i++) {
row += 1;
if (formulaArray.length == 797) {
sheet.getRange(headerRow, column).offset(0, 0, formulaArray.length).setValues(formulaArray);
} else {
formulaArray.push([formula + row + '")']);
}
Logger.log(formulaArray.length);
}
Logger.log(i)
formulaArray = [];
}
}
Here is where you might be making an error - you need to create the variable i (var i = 0 instead of just i = 0) and if you're nesting loops, you need to have different variables increasing (first loop use i, then nest with j, then nest in that with k etc as needed)
for(var i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(var j = 0; j < 797; j++) {
Untested but I believe it should work if you just substitute that in.
Your problem is in your loops. You are using the 'i' variable twice. Change the for loop that you have nested to iterate over the variable 'j' or something other than 'i'.

AS3 Picking a random object from an Array with certain conditions

I'm looking for the fastest way to pick a random object that has a certain condition (from an array).
In the example below I have a multidimensional array, 50 * 50 that contains objects. I want to pick a random object from that array but that object needs to have a size larger than 100.
while (object.size <= 100)
{
attempts++;
object = grid_array[Math.round(Math.random() * 49)][Math.round(Math.random() * 49)];
}
Currently I have tested this and in some instances it takes over 300+ attempts. Is there a more elegant way to do this?
Thanks,
What I would do is first filter the source array to extract only valid candidates, then return a random one (if there are any).
For example:
function getRandomObject(grid_array:Array, minSize:Number):Object {
var filtered:Array = [];
for(var i:int = 0; i < grid_array.length; i++){
var inner:Array = grid_array[i];
for(var ii:int = 0; ii < inner.length; ii++){
var object:Object = inner[ii];
if(object.size >= minSize){
filtered.push(object);
}
}
}
return filtered.length ? filtered[int(Math.random() * filtered.length)] : null;
}
// example:
var object:Object = getRandomObject(grid_array, 100);
if(object){
// do stuff with `object`
}
I asked if you need the indexes because you could do this with RegExps and the JSON Class (Flash Player 11). With this example I stored the indexes of the objects:
Create random multidimensional Array to test the function
//---I stored a variable size and the indexes inside the Object
//---Size variable will be numbers between 0 and 500
var array:Array = [];
var i;
var j;
var size:uint = 50;
var obj:Object;
for(i = 0; i < size; i++){
array[i] = [];
for(j = 0; j < size; j++){
obj = new Object();
obj.size = Math.floor(Math.random() * 500);
obj.files = i;
obj.columns = j;
array[i][j] = obj;
}
}
Method to get random Object with size property bigger than 100
//---I'll use to search the object a JSON string
var str:String = JSON.stringify(array);
//---Function to get the random Object
function getRandom():Object{
//---RegExp to search object with size between 100 and 500
var reg:RegExp = /\{[^\}]*"size":(?:10[1-9]|1[1-9]\d|[2-5]\d\d)[^\}]*\}/g;
//---Get all matches
var matches:Array = str.match(reg);
//---Return a random match converted to object
//---If no match founded the return will be null
return matches ? JSON.parse( matches[Math.floor(Math.random() * matches.length)] ) : null;
}

Minimum number of swaps needed to sort the array

I have an array of size n, which contain elements from 1 to n, in random order. So, we'd have as input an unordered array of integers.
Considering I can swap any two elements any number of times, how can I find minimum numbers of such swap to make array sorted?
This can be done in O(n). Assuming elements are in range 1 to n and there're no duplicates.
noofswaps = 0
for i in range(len(A)):
while A[i] != i + 1:
temp = A[i]
A[i] = A[A[i] - 1]
A[temp - 1] = temp
noofswaps += 1
print noofswaps
static int minimumSwaps(int[] arr) {
int swap=0;
boolean newarr[]=new boolean[arr.length];
for(int i=0;i<arr.length;i++){
int j=i,count=0;
while(!newarr[j]){
newarr[j]=true;
j=arr[j]-1;
count++;
}
if(count!=0)
swap+=count-1;
}
return swap;
}
I'll try to answer this question using javascript.
This is most optimal code I have tried so far :
function minimumSwaps(arr) {
var arrLength = arr.length;
// create two new Arrays
// one record value and key separately
// second to keep visited node count (default set false to all)
var newArr = [];
var newArrVisited = [];
for (let i = 0; i < arrLength; i++) {
newArr[i]= [];
newArr[i].value = arr[i];
newArr[i].key = i;
newArrVisited[i] = false;
}
// sort new array by value
newArr.sort(function (a, b) {
return a.value - b.value;
})
var swp = 0;
for (let i = 0; i < arrLength; i++) {
// check if already visited or swapped
if (newArr[i].key == i || newArrVisited[i]) {
continue;
}
var cycle = 0;
var j = i;
while (!newArrVisited[j]) {
// mark as visited
newArrVisited[j] = true;
j = newArr[j].key; //assign next key
cycle++;
}
if (cycle > 0) {
swp += (cycle > 1) ? cycle - 1 : cycle;
}
}
return swp;
}
reference -1
reference -2
Hackerrank Python code for minimum swaps 2 using hashmaps
length = int(input())
arr= list(map(int,input().split()))
hashmap = {}
for i in range(0,len(arr)):
hashmap[i+1] = [arr[i],False]
swap_count = 0
for e_pos, e_val in hashmap.items():
if e_val[1] == False:
e_val[1] = True
if e_pos == e_val[0]:
continue
else:
c = e_val[0]
while hashmap[c][1] == False:
hashmap[c][1] = True
b = hashmap[c][0]
c = b
swap_count+=1
print(swap_count)
There's an interesting take in GeeksForGeeks with
Time Complexity: O(N) where N is the size of the array.
Auxiliary Space: O(1)
The used approach was
For each index in arr[], check if the current element is in it’s right position or not. Since the array contains distinct elements from 1 to N, we can simply compare the element with it’s index in array to check if it is at its right position.
If current element is not at it’s right position then swap the element with the element which has occupied its place (using temp variable)
Else check for next index (i += 1)
This is the code
def minimumSwaps(arr):
min_num_swaps = 0;
i = 0;
while (i < len(arr)):
if (arr[i] != i + 1):
while (arr[i] != i + 1):
temp = 0;
temp = arr[arr[i] - 1];
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
min_num_swaps += 1;
i += 1;
return min_num_swaps;
that could easily be updated to
Remove semicolons
Remove the need for temp
Substitute len(arr) with a given integer input n with the size of the array
def minimumSwaps(arr):
min_num_swaps = 0
i = 0
while (i < n-1):
if (arr[i] != i + 1):
while (arr[i] != i + 1):
arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]
min_num_swaps += 1
i += 1;
return min_num_swaps
They both are gonna pass all the current 15 Test cases in HackerRank
Here is my code for minimumsawap function using java 7
static int minimumSwaps(int[] arr) {
int c=0;
for(int i=0;i<arr.length;i++){
if(arr[i]!=(i+1)){
int t= arr[i];
arr[i]=arr[t-1];
arr[t-1]=t;
c++;
i=0;
}
}
return c;
}

Adding a fixed number of unique items to an array using a for loop and indexOf

I'm using a for loop to get 6 random numbers between 1-20, using indexOf to omit duplicates, and pushing them to an array.
However, I always want 6 items in the array, so I'd like duplicates to be replaced. In my naive code duplicates are simply omitted, which means that sometimes I'll get less than 6 in the array. How do I replace the omissions to fill those 6 array slots?
function rolld(event:MouseEvent) {
for (i = 0; i < 6; i++){
d = (Math.floor(Math.random() * (1 + d_hi - d_lo)) + d_lo);
if (rollArray.indexOf(d) < 0){
rollArray.push(d);
}
}
trace (rollArray);
}
Still very new to this. Thanks for any help!
When you get an element from array with 20 elements, try to remove it from array.
function rolld(event:MouseEvent) {
var elements:Array = [];
for (var i:int = 1; i <= 20; i++)
{
elements.push(i);
}
for (i = 0; i < 6; i++){
d = (Math.floor(Math.random() * elements.length);
rollArray.push(d);
//remove the element
elements.splice(d, 1);
}
trace (rollArray);
}

input an array output bigger array related to input

suppose I have a arrays from each i want to produce b these are just examples
a=[4]=> b=[0,4]
a=[3,1]=>b=[0,3,3,4]
a=[2,2]=>b=[0,2,2,4]
a=[2,1,1]=>b=[0,2,2,3,3,4]
a=[3,4,2,5]=>b=[0,3,3,7,7,9,9,14]
I mean when getting 4 it should produce from 0 and then add it to it's content for example 4
or in a[2,1,1] first it will produce 0 and then it see that the next one in a is 1 so after again producing it it will compute 2+1 and assign it.so the output always will be twice size of the input.
i want a pseudo code for it my problem is that when it will repeat I can not write it.
I used JavaScript like syntax.
var a = new Array(3,4,2,5);
var b = new Array();
var bArrayIndex = 0;
b[bArrayIndex] = 0;
bArrayIndex++;
for(i = 0; i < a.length; i++) {
b[bArrayIndex] = b[bArrayIndex-1] + a[i];
if(i < a.length - 1) {
b[bArrayIndex+1] = b[bArrayIndex];
}
bArrayIndex+=2;
}
for(i = 0; i < b.length; i++) {
document.write(b[i] + " ");
}

Resources