How to reverse the array with the function reverseArray - javascript

You are given an array with N length. Please develop the function reverseArray to reverse the array
E.g.
Input: [1, 2, 3, 4, 5]
Output:
5
4
3
2
1
My attempt is as follows:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
for (var i = inputArray.length - 1; i >= 0; i--){
inputArray.push(inputArray[i]);
}
printArray(inputArray);
}
reverseArray([1, 2, 3, 4, 5]);
But it turns out to be as follows:
1 2 3 4 5 5 4 3 2 1
Can anyone teach me how to solve, i have been struggling with this question for 2 days

Check
this link
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);

You can use reverse() and join()
var arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr.join(' '));

Use for loop:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
var results = [];
for (var i = inputArray.length - 1; i >= 0; i--){
results.push(inputArray[i]);
}
printArray(results);
}
reverseArray([1, 2, 3, 4, 5]);
User array's reverse method:
function printArray (inputArray){
for(let i = 0; i < inputArray.length; i++){
console.log(inputArray[i]);
}
}
function reverseArray (inputArray){
var results = [];
results = inputArray.reverse();
printArray(results);
}
reverseArray([1, 2, 3, 4, 5]);

A bit change on your base code. It could be simpler, but I think what you need is a inplace reverse.
function printArray(inputArray) {
for (let i = 0; i < inputArray.length; i++) {
console.log(inputArray[i]);
}
}
function reverseArray(inputArray) {
const tempArr = inputArray.slice();
inputArray.splice(0, inputArray.length);
for (var i = tempArr.length - 1; i >= 0; i--) {
inputArray.push(tempArr[i]);
}
printArray(inputArray);
}
reverseArray([1, 2, 3, 4, 5]);

there are many ways to do this. and there is a reverse method for array too.
function reverseArray(inputArray) {
let start = 0;
let end = inputArray.length -1;
while (start < end) {
const tmp = inputArray[start];
inputArray[start] = inputArray[end];
inputArray[end] = tmp;
start++;
end--;
}
}
arr = [1, 2, 3, 4, 5];
reverseArray(arr);
console.log(arr);

thats very simple you can use javascript method "reversed()"
or you can use this function
function reverse(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var arr = [3,5,7,8]
var b = reverse(arr)
console.log(b)

The easiest method for reserve array is using Array.reverse;
But if you want do it by yourself,you can do it like this:
function reserveArray (input){
for (let i =0;i<input.length;i++){
input.unshift(input.pop())
}
}
It's just an idea, and i do not test if it run as expected.

You could iterate through half the array and swap [i] and [inputArray.length-1-i].
function reverseArray(a) {
for(let i = 0; i < Math.floor(a.length / 2); i++) {
[a[i], a[a.length - 1 - i]] = [a[a.length - 1 - i], a[i]];
}
}
If the output is really a string (opposed to an array) just print the elements start from the end:
function reverseArray(a) {
for(let i = a.length - 1; i >= 0; i--) {
process.stdout.write(a[i].toString() + (i ? " " : ""));
}
}

Related

equivalent of python's array.pop() in javascript

I wonder if there's an easy to implement equivalent to python's array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let j = 0; j < nums.length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
arr.push(nums.splice(smallest_index, 1).join(""));
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
it seems that if I replace javascript's (nums.splice(smallest_index, 1).join()) with python's (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?
OK, you use splice. Here's an example of the implementation below:
Array.prototype.pythonPop = function (index) {
return this.splice(index, 1)[0];
}
Now, I found the issue, you'll love the answer. So you were using num.length but your methods were augmenting the length of num array. Which is why your answer had only half the needed numbers. See code below. I cached the length prop of nums array
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
console.log(nums)
for (let j = 0, length = nums.length; j < length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
console.log(nums)
arr[j] = nums.splice(smallest_index, 1).join("");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums))

I'm trying to exclude elements from an Array, but I'm doing somthing wrong

I'm trying to create this script: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy
After the comment "Verify and delete" is where I have the problem.
I try to check all the elements form the array 'theCheck' with the elements from 'destroyers' and if the elements dont match then the script will push that value to the output array.
But it pushes every element regardless.
Expected output value: [1,1]
Current output value value: [1,2,3,1,2,3]
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] !== destroyers[j]) {
output.push(theCheck[i])
break;
}
}
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
With the current code you're looping through the destroyers and anytime you find a destroyer that doesn't match the item you're checking you're adding it to the output. But because you've got two items in the destroyers array it is guaranteed that one of the two is not going to match the particular item that you're checking.
Below is a version where we work out whether any of the destroyers are found to match the item that we're checking, and only if it doesn't we're adding it to the output:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
let found = false;
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] === destroyers[j]) {
found = true;
}
}
if(!found) output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You could use the includes function to tidy this up a little:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
if(!destroyers.includes(theCheck[i]))
output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(input, ...arr) {
return input.filter(element => !arr.includes(element));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

JavaScript: calculate the average of an odd number

I want to count the average value of the odd numbers from a list of numbers. I have a starting code to count the average, but I don't know how can I choose only the odd numbers from the list?
Here is my code:
var numberArray = [1,2,3,4,5,6], thisTotal=0,thisAverage=0;
for (var i=0; i<numberArray.length; i++) {
thisTotal += numberArray[i];
}
thisAverage = (thisTotal/numberArray.length);
alert(thisAverage)
You can use a filter function to return only the odd numbers:
var oddArray = numberArray.filter(function(val) {
return val % 2 !== 0;
});
Full example:
var numberArray = [1, 2, 3, 4, 5, 6];
var thisTotal = 0;
var thisAverage = 0;
var oddArray = numberArray.filter(function(val) {
return val % 2 !== 0;
});
console.log(oddArray); // [1, 3, 5]
var thisTotal = oddArray.reduce(function(accumulator, currentValue) { return accumulator + currentValue;
});
console.log(thisTotal); // 1 + 3 + 5 => 9
var thisAverage = thisTotal / oddArray.length;
console.log(thisAverage); // 9 / 3 => 3
var numberArray=[1,2,3,4,5,6], thisAverage=0,oddlength=0;
for(var i=0;i<numberArray.length;i++)
{
if(numberArray[i]%2!==0){
thisAverage+=numberArray[i];
oddlength++;
}
}
thisAverage=(thisAverage/oddlength);
alert(thisAverage)
Well, you can get what you want by this.
var numberArray=[1,2,3,4,5,6], thisTotal=0,thisAverage=0;
for(var i=0; i < 3; i++) {
thisTotal += numberArray[i * 2];
thisAverage= (thisTotal/numberArray.length);
}
console.log(thisAverage);
or if you want general solution, use this.
var numberArray=[1,2,3,4,5,6,7,8,...on and on], thisTotal=0,thisAverage=0;
for(var i=0; i < Math.ceil(numberArray.length() / 2); i++) {
thisTotal += numberArray[i * 2];
thisAverage= (thisTotal/numberArray.length);
}
console.log(thisAverage);
hope my code be helpful :)
You can use the function reduce to add and count.
var numberArray = [1, 2, 3, 4, 5, 6],
result = numberArray.reduce((a, n) => {
if (n % 2 !== 0) {
a.sum += n;
a.count++;
}
return a;
}, {sum: 0, count: 0}),
average = result.sum / result.count;
console.log(average);
Assuming the numbers are in an array, you can do this:
var numbers = [1, 2, 3, 4, 5, 6];
var info = numbers.filter(function(n) { return n % 2 !== 0})
.reduce(function(acc, item) {
return {sum: acc.sum + item, count: acc.count + 1}
}, {sum: 0, count: 0});
var avg = info.sum / info.count;
This example uses filter and reduce methods, which are declarative and more clear.
filter returns a new array with the items for which the function returns true, and then reduce, for each item, updates an 'accumulator'. The accumulator can be anything, and in this case is an object with the sum of the numbers and their count. For each item, we add add the current number to the sum property and add 1 to count. Finally, we just devide sum by count and done.
var acc = 0, oddCount = 0;
for(var i = 0; i < numberArray.length; i++) {
if(numberArray[i] % 2 !== 0) {
acc += numberArray[i];
oddCount++;
}
}
return acc / oddCount;
You can create a new array and store odd values in that array and after that you can apply your logic to that array.
var a=[1,2,3,4,5,6,10,11];
var ar=[];
for (var i = 0; i < a.length; i++) {
if(a[i] % 2 !== 0) {
ar.push(a[i]);
}
}
console.log(ar);
var numberArray=[1,2,3,4,5,6,7,8];
var count = 0;
var result = 0;
for (let i = 0; i <= (numberArray.length-1); i++)
{
if (numberArray[i] % 2 != 0)
{
result += numberArray[i];
count++;
}
}
alert(result / count);

javascript program returns a number instead of the desired array

I have a program that's supposed to remove items from a list of arguments
function destroyer(arr) {
var args = [].slice.call(arr);
var data = args.shift();
for(var i = 0; i < args.length; i++){
var j = 0;
while(j < data.length){
if(args[i] == data[j]){
data.splice(j,1);
j = 0;
}
else{
j += 1;
}
}
}
return data;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3) is supposed to return [1,1] but I'm only getting a response of 1, and I'm not sure why because when I perform the instruction outside the loop, I get the array.
Update: Should look like this.
function destroyer(arr) {
var args = [].slice.call(arguments);
var data = args[0];
args.shift();
for(var i = 0; i < args.length; i++){
var j = 0;
while(j < data.length){
if(args[i] == data[j]){
data.splice(j,1);
j = 0;
}
else{
j += 1;
}
}
}
// Remove all the values
return data;
}
As an alternative, you can use spread syntax to get the array of elements to remove and Array.prototype.filter to filter out these elements, like so
function destroyer(arr, ...args) {
return arr.filter(e => !args.includes(e));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // [1, 1]
You should use the spread syntax to indicate that there will be more parameters
function destroyer(...arr) {
var args = [].slice.call(arr);
var data = args.shift();
for(var i = 0; i < args.length; i++){
var j = 0;
while(j < data.length){
if(args[i] == data[j]){
data.splice(j,1);
j = 0;
}
else{
j += 1;
}
}
}
return data;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Yet another variant.
function destroyer(array) {
var pos, args = [].slice.call(arguments, 1),
arrLength = array.length,
newArray = [];
while ((arrLength -= 1) >= 0) {
pos = args.lastIndexOf(array[arrLength]);
if (!~pos) {
newArray.unshift(array[arrLength]);
}
}
return newArray;
};
console.log(destroyer([1,2,3,1,2,3], 2, 3));
console.log(destroyer([1,2,3,1,2,3], 1, 3));
console.log(destroyer([1,2,3,1,2,3], 1, 2));
console.log(destroyer([1,2,3,1,2,3], 1, 2, 3));
console.log(destroyer([1,2,3,1,2,3], 4));

Output each combination of an array of numbers with javascript

I have several numbers in an array
var numArr = [1, 3, 5, 9];
I want to cycle through that array and multiply every unique 3 number combination as follows:
1 * 3 * 5 =
1 * 3 * 9 =
1 * 5 * 9 =
3 * 5 * 9 =
Then return an array of all the calculations
var ansArr = [15,27,45,135];
Anyone have an elegant solution? Thanks in advance.
A general-purpose algorithm for generating combinations is as follows:
function combinations(numArr, choose, callback) {
var n = numArr.length;
var c = [];
var inner = function(start, choose_) {
if (choose_ == 0) {
callback(c);
} else {
for (var i = start; i <= n - choose_; ++i) {
c.push(numArr[i]);
inner(i + 1, choose_ - 1);
c.pop();
}
}
}
inner(0, choose);
}
In your case, you might call it like so:
function product(arr) {
p = 1;
for (var i in arr) {
p *= arr[i];
}
return p;
}
var ansArr = [];
combinations(
[1, 3, 5, 7, 9, 11], 3,
function output(arr) {
ansArr.push(product(arr));
});
document.write(ansArr);
...which, for the given input, yields this:
15,21,27,33,35,45,55,63,77,99,105,135,165,189,231,297,315,385,495,693
I think this should work:
var a = [1, 3, 5, 9];
var l = a.length;
var r = [];
for (var i = 0; i < l; ++i) {
for (var j = i + 1; j < l; ++j) {
for (var k = j + 1; k < l; ++k) {
r.push(a[i] * a[j] * a[k]);
}
}
}
Edit
Just for my own edification, I figured out a generic solution that uses loops instead of recursion. It's obvious downside is that it's longer thus slower to load or to read. On the other hand (at least on Firefox on my machine) it runs about twice as fast as the recursive version. However, I'd only recommend it if you're finding combinations for large sets, or finding combinations many times on the same page. Anyway, in case anybody's interested, here's what I came up with.
function combos(superset, size) {
var result = [];
if (superset.length < size) {return result;}
var done = false;
var current_combo, distance_back, new_last_index;
var indexes = [];
var indexes_last = size - 1;
var superset_last = superset.length - 1;
// initialize indexes to start with leftmost combo
for (var i = 0; i < size; ++i) {
indexes[i] = i;
}
while (!done) {
current_combo = [];
for (i = 0; i < size; ++i) {
current_combo.push(superset[indexes[i]]);
}
result.push(current_combo);
if (indexes[indexes_last] == superset_last) {
done = true;
for (i = indexes_last - 1; i > -1 ; --i) {
distance_back = indexes_last - i;
new_last_index = indexes[indexes_last - distance_back] + distance_back + 1;
if (new_last_index <= superset_last) {
indexes[indexes_last] = new_last_index;
done = false;
break;
}
}
if (!done) {
++indexes[indexes_last - distance_back];
--distance_back;
for (; distance_back; --distance_back) {
indexes[indexes_last - distance_back] = indexes[indexes_last - distance_back - 1] + 1;
}
}
}
else {++indexes[indexes_last]}
}
return result;
}
function products(sets) {
var result = [];
var len = sets.length;
var product;
for (var i = 0; i < len; ++i) {
product = 1;
inner_len = sets[i].length;
for (var j = 0; j < inner_len; ++j) {
product *= sets[i][j];
}
result.push(product);
}
return result;
}
console.log(products(combos([1, 3, 5, 7, 9, 11], 3)));
A recursive function to do this when you need to select k numbers among n numbers. Have not tested. Find if there is any bug and rectify it :-)
var result = [];
foo(arr, 0, 1, k, n); // initial call
function foo(arr, s, mul, k, n) {
if (k == 1) {
result.push(mul);
return;
}
var i;
for (i=s; i<=n-k; i++) {
foo(arr, i+1, mul*arr[i], k-1, n-i-1);
}
}
This is a recursive function.
First parameter is array arr.
Second parameter is integer s. Each call calculates values for part of the array starting from index s. Recursively I am increasing s and so array for each call is recursively becoming smaller.
Third parameter is the value that is being calculated recursively and is being passed in the recursive call. When k becomes 1, it gets added in the result array.
k in the size of combination desired. It decreases recursively and when becomes 1, output appended in result array.
n is size of array arr. Actually n = arr.length
var create3Combi = function(array) {
var result = [];
array.map(function(item1, index1) {
array.map(function(item2, index2) {
for (var i = index2 + 1; i < array.length; i++) {
var item3 = array[i];
if (item1 === item2 || item1 === item3 || item2 === item3 || index2 < index1) {
continue;
}
result.push([item1, item2, item3]);
}
});
});
return result;
};
var multiplyCombi = function(array) {
var multiply = function(a, b){
return a * b;
};
var result = array.map(function(item, index) {
return item.reduce(multiply);
});
return result;
}
var numArr = [1, 3, 5, 9];
// create unique 3 number combination
var combi = create3Combi(numArr); //[[1,3,5],[1,3,9],[1,5,9],[3,5,9]]
// multiply every combination
var multiplyResult = multiplyCombi(combi); //[15,27,45,135];
https://github.com/dankogai/js-combinatorics
Found this library. Tested to be working. Below is from the library document:
var Combinatorics = require('js-combinatorics');
var cmb = Combinatorics.combination(['a','b','c','d'], 2);
while(a = cmb.next()) console.log(a);
// ["a", "b"]
// ["a", "c"]
// ["a", "d"]
// ["b", "c"]
// ["b", "d"]
// ["c", "d"]
Using node, you can do this pretty easily using a library. First install bit-twiddle using npm:
npm install bit-twiddle
Then you can use it in your code like this:
//Assume n is the size of the set and k is the size of the combination
var nextCombination = require("bit-twiddle").nextCombination
for(var x=(1<<(k+1))-1; x<1<<n; x=nextCombination(x)) {
console.log(x.toString(2))
}
The variable x is a bit-vector where bit i is set if the ith element is contained in the combination.

Categories

Resources