input an array output bigger array related to input - arrays

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] + " ");
}

Related

Google App Script breaking singular element into 1D array with several elements

I've created a custom script in GAS (for Google Sheets) so I could join several data sources into one unique display. I added a .splice in the middle so I could cut out all null elements inside the arrays (which meant removing blank rows in the return array).
Here is it how the code goes:
function COMPILER(){
var i;
var c;
var r;
var display = [];
for (i = 0; i < arguments.length; i++) {
for (c = 0; c < arguments[i].length;c++) {
display.push(arguments[i][c]);
};};
for (r = display.length-1; r >= 0; r--) {
if (display[r][1]==""){
display.splice(r, 1)
};};
return display
};
The code works fine with 2+D arrays and with 1D arrays that have 2+ elements; but when its working with 1D arrays that have only one element, it unintendedly breaks down the strings into several elements.
Instead of returning:
ar1
ar2
It returns
a
r
1
a
r
2
How could I solve this?
I think/assume this is what you're trying to do:
function COMPILER()
{
var display = [];
for(var i = 0, numArguments = arguments.length; i < numArguments; ++i)
{
//console.log([i, arguments[i], Array.isArray(arguments[i])]);
if(Array.isArray(arguments[i]))
{
for(var j = 0, len = arguments[i].length; j < len; ++j)
{
if(arguments[i][j] != "")
{
display.push(arguments[i][j]);
}
}
}
else if(arguments[i] != "")
{
display.push(arguments[i]);
}
}
return display;
}
I can't confirm/test cause I don't know how you're calling COMPILER.

Multiply each element from array by every element

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 ...

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'.

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);
}

Calculating h-index

I need to calculate the h-index from a list of publications i stored in a tree.
What i did is traversing the tree in decrescent order obtaining a list of position-number of citations
it looks like:
line 1 10
line 2 5
line 3 4
line 4 0
I should stop at line 3 and return 3. The problem is with the examples given and in this case
line 1 4
line 2 0
line 3 0
it stops at 2 because 4>1 but 0>3 is false. It should return 1 instead. Can you explain me why? I know it's more like a mathematician question, but after that i could need to re-implement it if something is deeply wrong.
Here is the code
int index_h_calc(rbtree_node n, int *i){
if (n == NULL) {
fputs("<empty tree>\n", stdout);
return 0;
}
if (n->right != NULL)
index_h_calc(n->right,i);
graduat *grad;
grad=n->value;
if(DEBUG)
printf("linea %d %d %s\n ",*i,(int)grad->tot,grad->name);
if(*i+1>=(int)grad->tot) {
return *i;
} else
*i+=1;
if (n->left != NULL)
index_h_calc(n->left,i);
return *i;
}
This has several solutions on github, eg in Ruby, equivalent to your n is citePages and being the h-index calculated
function h_index(){
var hArray = new Array();
var x = 0;
for(var i = 0; i < citePages.length; i++){
var citeArray = citePages[i];
for(var j = 0; j < citeArray.length; j++){
// The multiplication by one is a hack to convert the string type into a numerical type
hArray[x++] = citeArray[j]*1;
}
}
hArray.sort(sortNumber);
//alert(hArray);
for(var i = 0; i < hArray.length; i++){
if(i > hArray[i]){
return hArray[i-1];
}
}
}
previous function -
function getCitationCount(responseText){
if (responseText == null){
_gel("sContent").innerHTML = "<i>Invalid data.</i>";
alert("There is no data.");
return;
}
var cite_exists = 1;
var cite_str_len = 14;
var len_of_Cite_by_str = 9;
var citeArray = new Array();
for(var i = 0; cite_exists > 0; i++)
{
cite_exists = responseText.search('Cited by');
if(cite_exists == -1){
//alert("No more citations for given Author!");
//return;
}else{
var tmp_string = responseText.substr(cite_exists, cite_str_len);
var end = (tmp_string.indexOf("<")-len_of_Cite_by_str);
citeArray[i] = tmp_string.substr(len_of_Cite_by_str, end);
publications++;
responseText = responseText.substr(cite_exists+cite_str_len, responseText.length);
}
}
return citeArray;
}
If this doesn't provide a solution then the problem to be verifiable - so we really need example data, eg a jsfiddle of typical data stating what result is expected in each case, given that this is a mathematical rather than coding question and can only be tested with a populated complex data structure.
Perhaps I am missing some subtlety, but isn't the answer just to subtract one from the line number? That is, if i is the line number and n is the number of citations, you traverse the tree until you find a line with n < i and then return the h-index as i - 1.

Resources