I wrote the code, but for some reason it displays the index 1, 2, 3, while 3 + 4 will in no way be equal to target (6).
var twoSum = function(nums, target) {
let sum = [];
var n = 2;
for(let i = 0; i < nums.length; i++) {
for(let a = 1; a < nums.length; a++) {
if(nums[i] + nums[a] == target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};
console.log(twoSum([1,3,4,2],6))
Input
[1,3,4,2]
6
Output
[1,2]
Expected
[2,3]
As per my comment, start the inner loop at a = i + 1 to avoid summing numbers with themselves as well as to avoid checking the same combination twice, e.g (1, 2) and (2, 1):
var twoSum = function(nums, target) {
let sum = [];
let n = 2;
for (let i = 0; i < nums.length; i++) {
for (let a = i + 1; a < nums.length; a++) {
if (nums[i] + nums[a] === target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};
Related
I Need to get this output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
What I've tried so far:
function getPyramid() {
let nums = 0;
for (let i = 1; i <= 15; i++) {
for (let n = 1; n < i; n++) {
console.log(n);
}
console.log('<br/>');
}
return nums;
}
getPyramid();
It is possible to do with one single loop
function getPyramid() {
let nums = 0;
let count = 1;
let numbers = ''
for (let i = 0; i <= 15; i++) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + (i +1)
}
}
getPyramid();
Or like this you can specify amount of rows..
function getPyramid(rows) {
let nums = 0;
let count = 1;
let numbers = ''
let i = 1
while (count < rows + 1 ) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + i
i++;
}
}
getPyramid(5);
for (let i = 1 ; i <= 5; i++)
{
let s = []
for (let x = i * (i - 1) / 2 + 1; x <= i * (i + 1) / 2; x++)
{
s.push(x)
}
console.log(s.join(" "))
}
Apart from notes given by jnpdx in the comments, I'd add some:
for better convention between programmers we tend to name varible nested in for-loop: i, j
<br/> for HTML new line, In JS we do \n for that!
number++ is same number += 1
Conditional_Operator (expression)?true:false instead of if/else
function getPyramid(Lines) {
let number = 1; // the counter to display on each line of pyramid!
for (let i = 1; i <= Lines; i++) {
let str = '';//line to display
for (let j = 1; j <= i; j++) {
str += number++;//incrementing counter
str += j!=i ? ' ' : ''; //to make space, but not at the end of line.
}
console.log(str);//display that line
}
}
getPyramid(5);
A completely unnecessary attempt to do this in a functional style:
const ranged_array = (from, to) =>
Array.from({ length: to - from + 1 }, (_, i) => i + from);
const pyramid = (lines) =>
ranged_array(1, lines)
.reduce((a, v, i) => {
const prev = a[i - 1];
const last_num = prev && prev[prev.length - 1] || 0;
a.push(ranged_array(last_num + 1, last_num + v));
return a;
}, [])
.map((v) => v.join(' '))
.join("\n");
console.log(pyramid(5));
Input Arr=[1,2,3,4,5,6,7,8,9,10]
Expected output:-
Arr1 = [1,2,3,4,5,6,7] = 28
Arr2 = [8,9,10] = 27
The sum of arrays should be almost the same..
It can also be 3 or more parts
How to achieve this via custom function?
let Arr = [1,2,3,4,5,6,7,8,9,10]
const numberOfParts = 2
function SplitArr(Array, Parts){
/* ... */
}
let result = SplitArr(Arr,numberOfParts)
/* result should be [[1,2,3,4,5,6,7],[8,9,10]] */
/* output can be in any format as long as it can get the parts */
I think you can't do that directly by JS functions.
You have to create a custom function to achieve this.
I have considered dividing the array into 2 equal parts.
You can't always split the array equally. Here in this array, you can't partition array into more than 2 subparts, otherwise it will give more than 3 parts as some of the elements are present there having sum more than the partitioned Sum.
Note: I treated the array to be sorted, otherwise it depends on the usecase.
Note: I have updated the old implementation based on the updated question requirement
let arr=[1,2,3,4,5,6,7,8,9,10]
function splitArrayEqually(arr, parts=2){
//get the total sum of the array
let sum = arr.reduce((currentSum, value) => currentSum+value ,0);
//get the half sum of the array
let partitionedSum = Math.ceil(sum/parts);
let start=0, end=0, currentSum=0;
let splittedArray=[];
//get the index till which the sum is less then equal partitioned sum
while(end < arr.length){
if(currentSum+arr[end] > partitionedSum){
splittedArray.push(arr.slice(start,end));
start = end; //start new window from current index
currentSum = 0; //make sum =0
}
//add current end index to sum
currentSum += arr[end];
end++;
}
splittedArray.push(arr.slice(start));
return splittedArray;
}
splitted = splitArrayEqually(arr,3);
console.log(splitted)
let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const numberOfParts = 3
function sumOfArray(arr) {
if (arr) {
if (arr.length > 0) {
let sum = 0
for (let i = 0; i < arr.length; i++) sum += arr[i]
return sum
} else {
return 0
}
} else {
return 0
}
}
function SplitArr(Array, Parts) {
let lastIndex = 0
let result = []
function getReamingSum(arr) {
let psum = sumOfArray(Array.slice(lastIndex)) / Parts
console.log('psum ' + psum)
return psum + Parts
}
let psum = getReamingSum(Array)
for (let j = 0; j < Parts; j++) {
let total = 0
for (let i = 0; i < Array.length; i++) {
if (i >= lastIndex) {
total += Array[i]
if (total < psum || j === Parts - 1) {
if (result[j]?.length > 0) {
result[j].push(Array[i])
} else {
let arr = []
arr.push(Array[i])
result[j] = arr
}
lastIndex = i + 1
}
}
}
}
return result
}
let result = SplitArr(Arr, numberOfParts)
console.log(result)
Assuming the array isn't sorted,using a 2D array, with each sub array with sum almost equal to (sum of array / n).
let arr = [9,2,10,4,5,6,7,8,1,3]
arr.sort(function(a, b) { return a - b; });
const sum = arr.reduce((a, b) => a + b, 0);
const n = 2;
const result = [];
let s = 0;
let j = 0;
result[j] = [];
for(let i=0; i<arr.length; i++){
if(s <= Math.floor(sum/n)){
result[j].push(arr[i]);
s +=arr[i];
}
else{
s = 0;
j = j + 1;
result[j] = [];
result[j].push(arr[i]);
}
}
console.log(result)
O/P:
[ [1, 2, 3, 4,5, 6, 7], [ 8, 9, 10 ] ]
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const splitArray = (arr,parts) => {
const totalSum = arr.reduce((acc, item) => {
acc += item;
return acc;
}, 0)
const splitSum = Math.floor(totalSum / parts);
const arrObj = arr.reduce((acc, item,index) => {
acc.sum = acc.sum || 0;
acc.split = acc.split || {};
const pointer = Math.floor(acc.sum / splitSum);
//console.log(item,acc.sum, splitSum, pointer);
acc.split[pointer] = acc.split[pointer] || [];
acc.split[pointer].push(item);
acc.splitSum = splitSum;
acc.sum += item;
return acc;
}, {})
return arrObj;
}
console.log(splitArray(arr,2).split)
You're better off making a custom function:
let currentTotal = 0
let tempList = []
Arr.forEach(val => {
if (val >= 27) {
// push tempList to a new array
tempList = [];
currentTotal = val;
} else {
tempList.push(val);
currentTotal += val;
}
})
Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))
I am trying to get all subarray which have sum 0 in javascript ? I am able to do that in O(n^2) like this
function getSubArray(input){
let result =[]
sum= 0
let a = [];
for(var i =0;i<input.length;i++){
a=[];
sum =0 ;
for (let j = i; j < input.length; j++) {
a.push(input[j])
sum+=input[j];
if(sum ===0){
result.push(a);
}
}
}
return result
}
when I call above function console.log(getSubArray([1, 2, -3, 0, 4, -5, 2, -1])) it is printed in all subarray but in O(n^2).
I tried to optimism this in O(n) using map
function getSubArray1(input) {
let sum = 0,
map = {0:[-1]};
for (let i = 0; i < input.length; i++) {
sum += input[i];
if (!map[sum]) {
map[sum] = [i];
}else {
map[sum].push(i)
let val = map[sum];
for (let j = 0; j < val.length; j++) {
console.log(val[j])
}
}
}
}
above function not working not giving all subarray? is there any way to do this?
I take the reference from here
https://www.techiedelight.com/find-sub-array-with-0-sum/
That site has an article titled "Find subarrays with given sum in an array". It has C++, Java, and Python implementations.
I just ported the Java (and a bit of Python) code to JavaScript.
const main = () => {
const input = [4, 2, -3, -1, 0, 4], target = 0;
console.log(subarraySum(input, target));
console.log(subarraySumMap(input, target));
};
const subarraySum = (nums, k) => {
const results = [];
for (let start = 0; start < nums.length; start++) {
let sum = 0;
for (let end = start; end <= nums.length; end++) {
sum += nums[end];
if (sum === k) {
results.push(nums.slice(start, end + 1));
}
}
}
return results;
}
const subarraySumMap = (nums, k) => {
const insert = (hashMap, key, value) =>
hashMap.set(key, (hashMap.get(key) || []).concat(value));
const results = [], hashMap = new Map();
let sum = 0;
insert(hashMap, 0, -1);
for (let index = 0; index < nums.length; index++) {
sum += nums[index];
if (hashMap.has(sum - k)) {
let list = hashMap.get(sum - k);
list.forEach(value => {
results.push(nums.slice(value + 1, index + 1));
});
}
insert(hashMap, sum, index);
}
return results;
}
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
<!-- References: -->
<!-- https://leetcode.com/problems/subarray-sum-equals-k/solution/ -->
<!-- https://www.techiedelight.com/find-subarrays-given-sum-array/ -->
<!-- ∀ x ⊆ ∑ { 4, 2, -3, -1, 0, 4 } = 0 -->
I'm trying to get all the numbers that are higher than the average of a given Array.
(this goes into an HTML page so it's with document.write
this is what I wrote:
sumAndBigger(arrayMaker());
function sumAndBigger(array) {
for (i = 0; i < array.length; i++) {
sum += array;
}
var equalAndBigger = []
var avg = sum / array.length;
for (i = 0; i < array.length; i++) {
if (array[i] > avg) {
equalAndBigger.push(array[i])
}
}
document.write('The numbers are: ' + equalAndBigger)
}
function arrayMaker() {
var array = [];
for (i = 0; i < 5; i++) {
var entrie = +prompt('Enter a number: ');
array.push(entrie)
}
return array;
}
This doesn't seem to work.. what am I doing wrong here?
Thanks in advance!
Ok so here I am giving you a one-liner code to get all the elements from the array that are "strictly greater than" the average value
let array = [1, 2, 3, 4, 5]
let allNums = array.filter(v => v > array.reduce((x, y) => x + y) / array.length);
Explanation
array.reduce((x, y) => x + y) → sum of all elements in the array
array.reduce((x, y) => x + y) / array.length → getting the average
Output
[4, 5]
MORE DETAILED CODE
function getAverage(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
function getGreaterThanAverage(arr) {
let avg = getAverage(arr);
let numbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > avg) {
numbers.push(arr[i]);
}
}
return numbers;
}