How to get almost increasing sequence of integers - javascript

Given a sequence of integers as an array,i have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. Example
For sequence = [1, 3, 2, 1], the output should be
almostIncreasingSequence(sequence) = false
There is no one element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2] the output should be
almostIncreasingSequence(sequence) = true
We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].
The function must return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.
Here is what i have already tried , but it doesnt work for all situations
function almostIncreasingSequence(sequence) {
for (var i = 0; i < sequence.length; i++) {
if (sequence[i] > sequence[i + 1]) {
sequence.splice(i, 1);
return true;
};
return false;
};
}

function almostIncreasingSequence(sequence) {
var found = false;
for (var i=0;i<sequence.length;i++) {
if(sequence[i] <= sequence[i-1]) {
if(found) {
return false;
}
found = true;
if(i === 1 || i + 1 === sequence.length) {
continue;
}
else if (sequence[i] > sequence[i-2]) {
sequence[i-1] = sequence[i-2];
}
else if(sequence[i-1] >= sequence[i+1]) {
return false;
}
}
}
return true;
}

Here is my solution.
First I look for a decreasing sequence. If none, then return true
If there is a decreasing sequence inside the array, I create two more arrays excluding the two items in the decreasing sequence, and check those two new arrays. If one of them has no decreasing sequences, then return true, otherwise return false
function indexOfFail(sequence) {
let index = null;
for (let i = 0; i < sequence.length -1; i++) {
if (sequence[i] >= sequence[i + 1]) {
index = i;
break;
}
}
return index;
}
function almostIncreasingSequence(sequence) {
let index = indexOfFail(sequence);
if (index == null) return true;
let tmp1 = sequence.slice(0);
tmp1.splice(index, 1); //remove failed item
if (indexOfFail(tmp1) == null) return true;
let tmp2 = sequence.slice(0);
tmp2.splice(index + 1, 1); //remove next item to failed item
if (indexOfFail(tmp2) == null) return true;
return false;
}

Here is my answer
function almostIncreasingSequence(sequence) {
if (isIncreasingSequence(sequence)) {
return true;
}
for (var i = 0; i < sequence.length > 0; i++) {
var tmpSequence = sequence.slice(0); // copy original array
tmpSequence.splice(i, 1);
if (isIncreasingSequence(tmpSequence)) {
return true;
}
}
return false;
}
function isIncreasingSequence(sequence) {
for (var i = 0; i < sequence.length - 1; i++) {
if (sequence[i] >= sequence[i + 1]) {
return false;
}
}
return true;
}
almostIncreasingSequence([1, 3, 2, 1]); // false
almostIncreasingSequence([1, 3, 2]); // true

function almostIncreasingSequence(seq) {
var bad=0
for(var i=1;i<seq.length;i++) if(seq[i]<=seq[i-1]) {
bad++
if(bad>1) return false
if(seq[i]<=seq[i-2]&&seq[i+1]<=seq[i-1]) return false
}
return true
}

My Python3 answer:
O(n) time and O(1) space
def almostIncreasingSequence(sequence):
counter = 0
for idx in range(1, len(sequence)):
# n is smaller or equal to n-1
if sequence[idx] <= sequence[idx-1]:
counter += 1
# checking if index to be checked is within bounds
if idx - 2 >= 0 and idx + 1 <= len(sequence)-1:
# n is smaller or equal to n-1 and n+1 is smaller or equal to n-1
print(sequence[idx], sequence[idx-2], sequence[idx+1], sequence[idx-1])
if sequence[idx] <= sequence[idx-2] and sequence[idx+1] <= sequence[idx-1]:
counter += 1
print(counter)
# return true if 1 or 0 in counter otherwise return false
return counter <= 1

I know post is old, but here is php solution to the problem
function almostIncreasingSequence($sequence){
$error = false;
$check_current_again = false;
for ($i = 0; $i + 1 < count($sequence); $i++) {
$next = $i + 1;
if($check_current_again){
$i = $i - 1;
}
$check_current_again = false;
if($sequence[$i] >= $sequence[$next]){
if($error){
return false;
}
$error = true;
if($i > 0 && $sequence[$i -1] >= $sequence[$i + 1]){
$check_current_again = true;
}
}
}
return true;
}

Solution of a question:
function almostIncreasingSequence(sequence) {
var inc = true;
for (var i = 0; i < sequence.length; i++) {
if (sequence[i] >= sequence[i + 1]) {
if (inc) {
inc = false;
}
else {
return false;
}
}
};
return true;
}
console.log(almostIncreasingSequence([1, 3, 2, 1])); // false
console.log(almostIncreasingSequence([1, 3, 2])); // true

I think sequence is not almost increasing if there is more than one number which is smaller than it's previous number:
function almostIncreasingSequence(sequence) {
var found = 0;
sequence.forEach((el, index) => {
var next= sequence[index + 1] || Infinity;
if (el >= next) {
found++;
}
});
return found <= 1;
}
console.log("1, 3, 2, 1: ", almostIncreasingSequence([1, 3, 2, 1]));
console.log("1, 3, 2: ", almostIncreasingSequence([1, 3, 2]));
console.log("1, 2, 5, 5, 5: ", almostIncreasingSequence([1, 2, 5, 5, 5]));
And even simpler and shorter with array.filter:
function almostIncreasingSequence(sequence) {
return sequence.filter((it, index) => it >= (sequence[index + 1] || Infinity)).length <= 1;
}
console.log("1, 3, 2, 1: ", almostIncreasingSequence([1, 3, 2, 1]));
console.log("1, 3, 2: ", almostIncreasingSequence([1, 3, 2]));
console.log("1, 2, 5, 5, 5: ", almostIncreasingSequence([1, 2, 5, 5, 5]));
console.log("1, 2, 4, 5, 5: ", almostIncreasingSequence([1, 2, 4, 5, 5]));

function Test(arr){
var set_once = false;
for (i=0; i<arr.length; i++){
if(arr[i+1] <= arr[i]){
if(!set_once){
set_once = true;
arr.splice(i+1,1);
i = i-1;
}else{
return false;
}
}
}
return true
}

Algorithm: An almost increasing sequence can only have one number that is smaller than its previous number, and it must not equal than the number before its previous number. Also, the previous number must not equal to the number after the current number.
Illustration: Consider the following 4 numbers:
a, b, c, d
a and c must not equal to each other, so are b and d. We must nest this condition within (b > c) condition.
Actual JavaScript code:
const almostIncreasingSequence = seq => {
let decrementCount = 0;
for (let i = 1; i < seq.length - 1; i ++) {
if (seq[i] <= seq[i - 1]) {
decrementCount++;
if (seq[i] <= seq[i - 2] && seq[i + 1] <= seq[i - 1]) {
return false;
}
}
}
return decrementCount <= 1;
}

Here is a solution in PHP
function almostIncreasingSequence($sequence) {
$foundOne = false;
for ($i = -1, $j = 0, $k = 1; $k < count($sequence); $k++) {
$deleteCurrent = false;
if ($sequence[$j] >= $sequence[$k])
{
if ($foundOne)
{
return false;
}
$foundOne = true;
if ($k > 1 && $sequence[$i] >= $sequence[$k])
{
$deleteCurrent = true;
}
}
if (!$foundOne)
{
$i = $j;
}
if (!$deleteCurrent)
{
$j = $k;
}
}
return true;
}

static bool almostIncreasingSequence(int[] sequence)
{
int counter = 0;
if (sequence.Length <3)
return true;
int prevNo = sequence.Min() - 1;
for (int i = 0; i < sequence.Length; i++)
{
if (counter < 2)
{
if (prevNo < sequence[i])
prevNo = sequence[i];
else
{
if (i == 0 || i == sequence.Length - 1)
{
counter += 1;
}
else if (i > 1)
{
if (sequence[i] <= sequence[i - 2])
{
if (prevNo < sequence[i + 1])
{
counter += 1;
}
else
{
counter += 2;
}
}
else
{
prevNo = sequence[i];
counter = counter + 1;
}
}
// {
if (i < sequence.Length - 2)
{
if (sequence[i] < sequence[i + 1])
{
counter = counter + 1;
prevNo = sequence[i];
}
else
{
counter += 1;
}
}
// }
if (counter >= 2)
return false;
}
}
}
return true;
}

Here is a python3 implementation of the same. took me a while. not that clean of a code
But take O(N) time and O(1) space so that's ok I guess.
In this case, I had used an approach where I maintained a counter variable and a pointer
I increased the counter by 1 each time the sequence was not in an increasing fashion.
and maintained a pointer to the index of the element which was out of sequence.
if the counter had value more than 1 then the sequence is breaking at 2 points and it almost increasing sequence can not be achieved. if the sequence was already in place then the counter would be zero.
the tricky part comes when the counter is 1
here we make use of the index variable which we maintained that is p
if the c == 1 and the index is 0 or the length of sequence then the element which is breaking the sequence is at the start or end which can be removed to obtain an increasing sequence.
and if that's, not the case. we check for the adjacent values and they are breaking any order or not.
if they are not breaking the order return True else its False. Hope I was able to help. Forgive the Bad indentation. I am new to the code editor at StackOverflow
def almostIncreasingSequence(sequence):
p = -1
c = 0
for i in range(1, len(sequence)):
if sequence[i-1] >= sequence[i]:
p = i
c += 1
if c > 1:
return False
if c == 0:
return True
if p == n -1 or p == 1:
return True
if sequence[p-1] < sequence[p+1] or sequence[p-2] < sequence[p]:
return True
return False

Here's an extremely dirty version of it.
Lately, I've been trying to make solutions that are language agnostic, so that I don't become dependent on functions for problem solving, but learn them later for whatever language I specialize in.
Perhaps one of the dirtiest ways to do it, but time complexity is O(3N) = O(N).
Space complexity is O(2N).
The logic comes from the fact that you only need to check for ONE missing element, so there is no need to do anything fancy, just save the index of that element and check the array without that element.
Because sometimes you can run into another element being the issue (particularly in the case of duplicates), you should save the index of both problem elements.
Again, extremely dirty, but it passes all test cases and time constraints.
function almostIncreasingSequence(sequence) {
let wrongindex = 0;
let nextwrongindex = 0;
for(let i = 0; i < sequence.length - 1; i++){
if(sequence[i] >= sequence[i + 1]){
wrongindex = i;
nextwrongindex = i+1;
}
}
let newArr = [];
let newArr2 = [];
for(let i = 0; i < sequence.length; i++){
if(i != wrongindex){
newArr.push(sequence[i]);
}
}
for(let i = 0; i < sequence.length; i++){
if(i != nextwrongindex){
newArr2.push(sequence[i]);
}
}
let isincreasingcount = 0;;
for(let i = 0; i < newArr.length - 1; i++){
if(newArr[i] >= newArr[i+1]){
isincreasingcount++;
}
}
for(let i = 0; i < newArr2.length -1; i++){
if(newArr2[i] >= newArr2[i+1]){
isincreasingcount++;
}
}
if(isincreasingcount > 1){
return false;
}
return true;
}

$sequence = [0, -2, 6, 8] (Expected Output: true)
$sequence = [123, -17, -5, 1, 2, 12, 41, 45] (Expected Output:
true)
$sequence = [10, 1, 2, 3, 4, 5, 6, 1] (Expected Output: false)
$sequence = [3, 5, 62, 98, 3] (Expected Output: true)
$sequence = [40, 49, 63, 10, 22, 30] (Expected Output: false)
This almostIncreasingSequence function will return the given Array is Increasing Sequence or not.
You can try the above array examples.
print_r(almostIncreasingSequence($sequence));
function almostIncreasingSequence($sequence){
$found = 0;
$status = true;
for ($i=0;$i<sizeof($sequence);$i++) {
if(($sequence[$i] <= #$sequence[$i-1]) && isset($sequence[$i-1])) {
$found++;
if($found > 1) $status = false;
if($sequence[$i] <= $sequence[$i-2] && $sequence[$i+1] <= $sequence[$i-1] && isset($sequence[$i+1])) $status = false;
}
}
return (($status == 0) ? $status : true);
}

Just for the diversity. That's how I solved it.
function almostIncreasingSequence(sequence) {
let failsSeq = new Array(sequence.length).fill(0);
for(let i=0; i<sequence.length; i++) {
if (sequence[i+1] && sequence[i] >= sequence[i+1]) {
failsSeq[i] += 1;
if (sequence[i+2] && sequence[i] >= sequence[i+2]) {
failsSeq[i] += 1;
}
if (sequence[i-1] && sequence[i+1] && sequence[i-1]>=sequence[i+1]) {
failsSeq[i] += 1;
}
}
}
const failsTotal = failsSeq.reduce( (acc, currValue) => acc + currValue);
const failSingle = failsSeq.filter( (item) => item >= 2 ).length;
if (failSingle === 1 && failsTotal === 2) {
return true;
}
return failsTotal > 1 ? false : true;
}

for eg 1,2,[5,3],6
We can solve this by 2 pointers, p2 will be ahead of p1 by 1 at the beginning. Once we found that, from the eg, 5 > 3, we need to skip each and check if the sequence is still valid, for that reason we call increasingSeq(), and skip 5 by (p1 -1). Then we skip 3 by (p2 + 1).
Once we skip those we start comparing the sequence again.
function almostIncreasingSequence(sequence) {
if (sequence.length < 2) return true;
let p1 = 0;
let p2 = 1;
while(p2 < sequence.length) {
if (sequence[p1] >= sequence[p2]) {
const a = increasingSeq(sequence, p1 - 1, p2);
const b = increasingSeq(sequence, p1, p2 +1 )
return a || b
}
p1 = p2;
p2++
}
return true;
}
function increasingSeq(sequence, p1, p2) {
while(p2 < sequence.length) {
if (sequence[p1] >= sequence[p2]) return false;
p1 = p2;
p2++
}
return true;
}

boolean almostIncreasingSequence(int[] sequence) {
int n = sequence.length;
if (n == 2)
{
return true;
}
int count = 0;
boolean result = true;
for (int i = 0; i < sequence.length - 1; i++)
{
if (sequence[i] >= sequence[i+1])
{
count++;
if (i != 0 && sequence[i-1] >= sequence[i+1])
{
result = false;
}
if (i < n-2 && sequence[i] < sequence[i+2])
{
result = true;
}
if (i == n - 2)
{
result = true;
}
}
}
return (count < 2 && result);
}

Here is a complete working solution:
function almostIncreasingSequence($s)
{
$bad=0;
for($i=1;$i<count($s);$i++)
{
if($s[$i]<=$s[$i-1]) $bad++;
if($bad>1) return false;
if(isset($s[$i+1]) && isset($s[$i-2]) && $s[$i]<=$s[$i-2] && $s[$i+1]<=$s[$i-1]) return false;
}
return true;
}

This is my optimized solution with python:
def solution(sequence):
if len(sequence) > 2:
for i in range(len(sequence)-1):
if sequence[i]>sequence[i+1]:
news = sequence[:i]+sequence[i+1:]
if news == sorted(news) and len(set(news)) == len(news):
return True
else:
news = sequence[:i+1]+sequence[i+2:]
if news == sorted(news) and len(set(news)) == len(news):
return True
return False
else:
return True

I've checked out that most proposals fails with the new tests added to codeSignal. My approach is not quite optimal but it's easy to understand.
First, I store into a hashmap the problematic indexes (the current and the previous one). After that you can run simulations of the array without the problematic items. It just simply minimizes the brute force approach and it passes all the test even with high amount of items.
Time complexity: O(N+N)
Space complexity: O(1)
Tests passed: 38/38.
Sample tests:
19/19
Hidden tests:
19/19
Score:
300/300
Edited: I added a "break" after first problematic number encountered in order to just handle the first issue. So time complexity now is better.
bool almostIncreasingSequence(vector<int> sequence) {
int length = sequence.size();
if (length < 2) {
return false;
}
// Store invalid indexes
unordered_map<int, int> m;
for(int i=1;i<length;++i) {
if (sequence[i-1] >= sequence[i]) {
m[i-1]++;
m[i]++;
break; // new added
}
}
// Scan invalid indexes
for(auto it : m) {
int prev = -1;
int numInvalid = 0;
const int id = it.first;
// Simulate
for(int i=0;i<length;++i) {
if (id!=i) { // Do not add the problematic one
if (prev != -1 && prev >= sequence[i]) {
++numInvalid;
break;
}
prev = sequence[i];
}
}
if (numInvalid == 0) {
return true;
}
}
return false;
}

Here is my PHP solution:
function almostIncreasingSequence($sequence) {
for($i=0;$i<count($sequence);$i++) {
$input = $sequence;
array_splice($input, $i, 1);
if(count($input) == count(array_unique($input))) {
$solution = $input;
sort($input);
if($solution == $input) {
return true;
}
}
}
return false;
}

My javascript answer for strictly increasing sequence.
function solution(sequence) {
for(let i =0;i<sequence.length;i++){
// first iteration
if((sequence[i]-sequence[i+1])>=0){
sequence.splice((i),1);
console.log('5', sequence);
// check again
for(let i = 0;i<sequence.length;i++){
if((sequence[i]-sequence[i+1])>=0){
console.log('9', sequence);
return false;
}
}
}
};
return true
}

boolean solution(int[] sequence) {
int count = 0;
for (int i = 1; i < sequence.length; i++) {
if (sequence[i] <= sequence[i-1]) {
// Increase count if we found a replace.
// return false if we found more than one
// replacements
count++;
if (count > 1) {
return false;
}
// Make sure you are within bounds of the array
// compare current index value with with previous
// two indices.
// finally compare values before and after the current
// index.
if (i - 2 > -1 && i+1 < sequence.length
&& sequence[i] <= sequence[i-2]
&& sequence[i+1] <= sequence[i-1]) {
return false;
}
}
}
return true;
}

Related

Javascript - simple exercises

I have a task to write a function getEvenAverage, which should take only one argument - array. This function should return an average value of even numbers from this array. If in the array there aren't any even numbers the function should return null.
I'd really appreciate any feedback :-)
function getEvenAverage(tab) {
{
if (i % 2 === 0) {
for (var i = 0; i < tab.length; i++) {
sum += parseInt(tab[i], 10);
}
var avg = sum / tab.length;
} else
console.log('null');
}
}
You say you need to return something, so return it. Also move your if statement inside your for loop, and fix a few other syntax errors. And as pointed out in the comments, you should divide sum by the number of even numbers to get your avg:
function getEvenAverage(tab) {
var sum = 0;
var evens = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
evens++;
}
}
if (evens == 0) {
console.log("null");
return null;
} else {
var avg = sum / evens;
return avg;
}
}
console.log(getEvenAverage([1, 2, 3]));
You could also do it with the array reduce, with a single array traversal
const reducer = (acc, val) => {
let {
sum,
count
} = acc;
return (val % 2 === 0 ? {
sum: sum + val,
count: count + 1
} : acc);
};
const getEvenAverage = (input) => {
const initialValue = {
sum: 0,
count: 0
};
const output = input.reduce(reducer, initialValue);
if (output.count === 0) {
return null;
} else {
return output.sum / output.count;
}
};
console.log(getEvenAverage([1, 2, 3]));
Here is the correct function.
function getEvenAverage(tab) {
var sum = 0, count = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
count++;
}
}
if(sum > 0)
return (sum / count);
return null;
}
Wish You happy coding.
Other than using a for loop, you can utilize filter and reduce Array methods.
function getEvenAverage(arr) {
const newArr = arr.filter(number => number % 2 === 0);
return newArr.length > 0 ? newArr.reduce((acc, num) => acc + num) / newArr.length : null;
}
console.log(getEvenAverage([1, 2, 3, 4]));
console.log(getEvenAverage([1, 3, 5, 7]));
Try this function,
function getEvenAverage(tab) {
var numberOfEvens = 0;
var sum = 0;
for(var i=0;i<tab.length;i++){
if(tab[i]%2 == 0 ){
numberOfEvens++;
sum += tab[i];
}
}
if(numberOfEvens == 0)return null;
return sum/numberOfEvens;
}
console.log(getEvenAverage([0,1,2,3,4,5]))
console.log(getEvenAverage([1,2,3,4,5]))
console.log(getEvenAverage([0,1,11,3,4,5]))
console.log(getEvenAverage([1,5,3]))
You need only the even numbers, so first filter the array into a new array, then sum all the numbers (using reduce or a for loop) and divide by its length.
function getEvenAverage(array) {
if (!Array.isArray(array)) return null; // not a must if you're sure you pass an array
var evenArray = array.filter(function(value) {
return value % 2 === 0
});
if (evenArray.length === 0) return null;
var evenSum = evenArray.reduce(function(total, current) {
return total + current;
});
var evenAvg = evenSum / evenArray.length;
return evenAvg;
}
console.log(getEvenAverage("not an array"));
console.log(getEvenAverage([1,3,7])); // no even numbers
console.log(getEvenAverage([1,2,3])); // single even number
console.log(getEvenAverage([2,2,2])); // only even numbers
console.log(getEvenAverage([1,2,3,10,18])); // bigger array
console.log(getEvenAverage([0,1])); // 0 is also even
function getEvenAverage(arr){
var evenNumbers = []; // we use an array to hold all of our evenNumbers
for (var el of arr){ // we loop over the received array to check the received
if(el % 2 !=0){ // if the number is even
evenNumbers.push(el); // we add it to our evenNumbers array
}
}
if(evenNumbers.length == 0){ // when we have no even Number
return false; // we then return false
}
else{
// the next block of code calculates the average of the even values
return evenNumbers.reduce((pv,cv) => pv+cv,0)/evenNumbers.length;
}
}
var evenNumbers = [4,2,3,6,5,9];
getEvenAverage(evenNumbers); // returns 5.666666666666667
getEvenAverage([2,4,6,8]); // returns false

JavaScript Quicksort recursive

I´m trying to implement a quicksort algorithm for an int array in JavaScript.
I´ve got a problem in my code. The first few ints get sorted well but at the end of the sortet array there is always one integer which is placed many times although its only one time in the array which should be sorted. Hopefully someone will find my fault.
Thanks.
function quicksort(array) {
var randomPlace = Math.round(Math.random() * array.length);
var pivotelement = array[randomPlace];
left = new Array;
right = new Array;
for (var i = 0; i < array.length; i++) {
if (array[i] < pivot) {
left[left.length] = array[i];
} else {
right[right.length] = array[i];
}
}
if ((left.length == 0 || left.length == 1) && (right.length == 0 || right.length == 1)) {
return left.concat(right);
} else if (left.length == 0 || left.length == 1) {
return (left.concat((quicksort(right))));
} else if (right.length == 0 || right.length == 1) {
return ((quicksort(left)).concat(right));
} else {
return (quicksort(left)).concat((quicksort(right)));
}
}
Beside some nameming confusion, like pivotelement vs pivot and Math.round vs Math.floor, you need to tackle the problem of for example [1, 1, 1] which is always returning left = [] and right = [1, 1, 1], that calls quicksort([1, 1, 1]) ad infinitum.
To overcome this problem, you need to check for empty left and with right every element, if it is equal to the random pivot. Then return right, without calling quicksort again.
function quicksort(array) {
var randomPlace = Math.floor(Math.random() * array.length),
pivot = array[randomPlace],
left = [],
right = [],
i;
for (i = 0; i < array.length; i++) {
(array[i] < pivot ? left : right).push(array[i]);
}
console.log(pivot, JSON.stringify(array), JSON.stringify(left), JSON.stringify(right));
// prevent looping forever
if (!left.length && right.every(function (v) { return v === pivot; })) {
return right;
}
if (left.length <= 1 && right.length <= 1) {
return left.concat(right);
}
if (left.length <= 1) {
return left.concat(quicksort(right));
}
if (right.length <= 1) {
return quicksort(left).concat(right);
}
return quicksort(left).concat(quicksort(right));
}
console.log(quicksort([2, 7, 4, 8, 3, 11, 49, 20, 10, 1, 1, 1]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another solution would be to separate the array into three arrays, one for smaller values, one for equal values and one for greater values. Then sort only the smaller and greater arrays.
function quicksort(array) {
var randomPlace = Math.floor(Math.random() * array.length),
pivotValue = array[randomPlace],
left = [],
pivot = [],
right = [],
i;
for (i = 0; i < array.length; i++) {
if (array[i] === pivotValue) {
pivot.push(array[i]);
continue;
}
(array[i] < pivotValue ? left : right).push(array[i]);
}
console.log(pivotValue, JSON.stringify(array), JSON.stringify(left), JSON.stringify(pivot), JSON.stringify(right));
if (left.length <= 1 && right.length <= 1) {
return left.concat(pivot, right);
}
if (left.length <= 1) {
return left.concat(pivot, quicksort(right));
}
if (right.length <= 1) {
return quicksort(left).concat(pivot, right);
}
return quicksort(left).concat(pivot, quicksort(right));
}
console.log(quicksort([2, 7, 4, 8, 3, 11, 49, 20, 10, 1, 1, 1]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
heres a short version of quick sort written in JS exactly as it is seen in Intro To Algorithms, hope this helps!
var partition = function (arr, low, high) {
var x = arr[high]
var i = low - 1
for (var j = low; j <= high - 1; j++) {
if (arr[j] <= x) {
i++
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
var temp = arr[i + 1]
arr[i + 1] = arr[high]
arr[high] = temp
return i + 1
}
var quickSort = function (arr, low, high) {
if (low < high) {
index = partition(arr,low,high)
if (low < index-1) quickSort(arr,low,index-1)
if (index+1 < high) quickSort(arr,index+1,high)
}
}
var list2 = [1000,13,12,1001,82,1,2,4,3,0]
console.log(quickSort(list2,0,list2.length))
also on my GitHub
I think you are identifying the randomPlace wrongly. It returns undefined some times because you're using Math.round().
Try this instead:
var randomPlace = Math.floor(Math.random() * array.length);
Also, use the following code when initializing left, and right:
var left = new Array();
var right = new Array();
Also, you need to change the pivot in array[i] < pivot to pivotElement.
You can see my complete fiddle here

What is the best way to shift a multidimensional array in Javascript?

I'm trying to create a javascript function that shifts an array right x units any up y units. It must keep the array size the same, and it must call unloadChunk for elements that are getting shifted off the multidimensional array. Here is my current implementation:
function shift(x, y) {
if (x > 0) {
for (var i = 0; i < chunks.length; i++) {
for (var j = chunks[i].length - 1; j >= 0; j--) {
if(j + x > chunks[i].length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
if (j < x) {
chunks[i][j] = null;
}
else {
chunks[i][j] = chunks[i][j - x];
}
}
}
}
else if (x < 0) {
for (var i = 0; i < chunks.length; i++) {
for (var j = 0; j < chunks[i].length; j++) {
if(j + x < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
if (j - x >= chunks[i].length) {
chunks[i][j] = null;
}
else {
chunks[i][j] = chunks[i][j - x];
}
}
}
}
if (y > 0) {
for (var i = 0; i < chunks.length; i++) {
if (i + y >= chunks.length) {
for (var j = 0; j < chunks.length; j++) {
if(i - y < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = null;
}
}
else {
for (var j = 0; j < chunks.length; j++) {
if(i - y < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = chunks[i + y][j];
}
}
}
}
else if (y < 0) {
for (var i = chunks.length - 1; i >= 0; i--) {
if (i + y < 0) {
for (var j = 0; j < chunks.length; j++) {
if(i - y > chunks.length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = null;
}
}
else {
for (var j = 0; j < chunks.length; j++) {
if(i - y > chunks.length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = chunks[i + y][j];
}
}
}
}
}
If you're having trouble understanding exactly what I want the shift function to do, take a look at this fiddle and look at the html output.
My attempt at creating the shift function works, but it has 10 for loops. My question was, is there a more efficient, less verbose way to do this?
This proposal uses
Array#forEach: visit each item
Array#map: return value for each item
Array#pop: removes and return last element
Array#push: adds one or more elements at the end
Array#shift: removes and return first element
Array#unshift: adds one or more elements at the beginning
For better visibillity, I replaced the null value with 1000, 2000, 3000 and 4000.
function shift(x, y) {
while (x > 0) {
chunks.forEach(function (a) {
a.pop();
a.unshift(1000);
});
x--;
}
while (x < 0) {
chunks.forEach(function (a) {
a.shift();
a.push(2000);
});
x++;
}
while (y > 0) {
chunks.unshift(chunks.pop().map(function () { return 3000; }));
y--;
}
while (y < 0) {
chunks.push(chunks.shift().map(function () { return 4000; }));
y++;
}
}
function print(msg) {
document.body.innerHTML += '<p>' + msg + '</p>';
}
function printarr(arr) {
for (var i = 0; i < arr.length; i++) {
print(JSON.stringify(arr[i]))
}
}
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
print("chunks: " + JSON.stringify(chunks));
shift(1, 0);
print("shifting right 1. chunks: "); printarr(chunks);
shift(-1, 0);
print("shifting left 1. chunks: "); printarr(chunks);
shift(0, 1);
print("shifting up 1. chunks: "); printarr(chunks);
shift(0, -1);
print("shifting down 1. chunks: "); printarr(chunks);
You can use pop(), push(), shift(), unshift() Array methods
var chunks = [
[5, 3, 1],
[9, 2, 5],
[2, 3, 7]
];
function shiftDown(){
chuck.pop();
chuck.unshift(Array(3));
}
function shiftUp(){
chuck.shift();
chuck.push(Array(3));
}
function shiftRight(){
chuck.foreach(function(v){
v.pop();
v.unshift(null);
})
}
function shiftLeft(){
chuck.foreach(function(v){
v.shift();
v.push(null);
})
}
If interpret Question correctly, you can use Array.prototype.forEach(), Array.prototype.splice()
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
// `x`: Index at which to start changing array
// `y`: An integer indicating the number of old array elements to remove
function shift(arr, x, y, replacement) {
arr.forEach(function(curr, index) {
// The elements to add to the array, beginning at the start index.
// start index: `x`
curr.splice(x, y, replacement)
});
return arr
}
// e.g.,
shift(chunks, -1, 1, null);
console.log(chunks);
it must call unloadChunk for elements that should be set to null
it's not a good idea to mutate an Array, while you're iterating over the same Array. So change unloadChunk() to not change chunks, but return the new value.
in my case I'm filling all the null values with new values.
then why do you bother to insert the null-values in the first place? why don't you just insert the new values?
//one-dimensional shift
function shift(arr, offset, callback){
var i, j, len = arr.length;
if(len && (offset |= 0)){
typeof callback === "function" || (callback = function(v){return v});
if(offset < 0){
for(i=-offset,j=0; i<len;)arr[j++]=arr[i++];
while(j<len)arr[j]=callback(null,j++,arr);
}else if(offset){
for(i=len-offset,j=len; i>0;)arr[--j]=arr[--i];
for(i=0; i<j;++i)arr[i]=callback(null,i,arr);
}
}
return arr;
}
//two dimensional shift
function shift2d(matrix, offsetX, offsetY, callback){
var i, len = matrix.length, tmp, fn;
offsetY |= 0;
offsetX |= 0;
if(len && matrix[0].length && (offsetY || offsetX)){
typeof callback === "function" || (callback = function(v){return v});
fn = function(val,j){ return callback(null, [i,j], matrix) };
tmp = {length: matrix[0].length};
offsetY && shift(matrix, offsetY, function(){return tmp});
for(i = 0; i < len; ++i){
if(matrix[i] === tmp){
matrix[i] = Array.from(tmp,fn);
}else{
shift(matrix[i], offsetX, fn);
}
}
}
return matrix;
}
and the code:
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
console.log(chunks);
console.log(shift2d(chunks, -1, 1));
console.log(shift2d(chunks, 1, -1, computeValue));
function computeValue(value, index, array){
console.log("value: %o index: %o, is chunks: %o", value, index, array === chunks);
//return the new value for this field
return JSON.stringify(index);
return Math.random();
//with ES6 array destructuring:
var [row,col] = index;
return row*3 + col;
}
shift() and shift2d() expect as the last argument an (optional) callback function that returns the new values.
For consistency reasons, I pass the same argument as Array.map and the others
value: always null, only there for consistency reasons
index: the "index" that is accessed. For shift2d this is an array of indices (take a look at array destructuring)
array: the current array/matrix. Don't mess around with this while it gets changed. The main reason to pass this argument, is to check wich Array you're currently processing.

Pair of elements from a specified array whose sum equals a specific target number

I am in mid of my JavaScript session. Find this code in my coding exercise. I understand the logic but I didn't get this map[nums[x]] condition.
function twoSum(nums, target_num) {
var map = [];
var indexnum = [];
for (var x = 0; x < nums.length; x++)
{
if (map[nums[x]] != null)
// what they meant by map[nums[x]]
{
index = map[nums[x]];
indexnum[0] = index+1;
indexnum[1] = x+1;
break;
}
else
{
map[target_num - nums[x]] = x;
}
}
return indexnum;
}
console.log(twoSum([10,20,10,40,50,60,70],50));
I am trying to get the Pair of elements from a specified array whose sum equals a specific target number. I have written below code.
function arraypair(array,sum){
for (i = 0;i < array.length;i++) {
var first = array[i];
for (j = i + 1;j < array.length;j++) {
var second = array[j];
if ((first + second) == sum) {
alert('First: ' + first + ' Second ' + second + ' SUM ' + sum);
console.log('First: ' + first + ' Second ' + second);
}
}
}
}
var a = [2, 4, 3, 5, 6, -2, 4, 7, 8, 9];
arraypair(a,7);
Is there any optimized way than above two solutions? Can some one explain the first solution what exactly map[nums[x]] this condition points to?
Using HashMap approach using time complexity approx O(n),below is the following code:
let twoSum = (array, sum) => {
let hashMap = {},
results = []
for (let i = 0; i < array.length; i++){
if (hashMap[array[i]]){
results.push([hashMap[array[i]], array[i]])
}else{
hashMap[sum - array[i]] = array[i];
}
}
return results;
}
console.log(twoSum([10,20,10,40,50,60,70,30],50));
result:
{[10, 40],[20, 30]}
I think the code is self explanatory ,even if you want help to understand it,let me know.I will be happy enough to for its explanation.
Hope it helps..
that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming
In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.
Lets investigate how it works to better understand it:
twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler
In iteration 0:
value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.
So in our map, 40 points to 0.
In iteration 2:
value is 40. I look at map my map to see I previously found a pair for 40.
map[nums[x]] (which is the same as map[40]) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.
Does that make any sense now?
Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)
Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)
function twoSum(arr, S) {
const sum = [];
for(let i = 0; i< arr.length; i++) {
for(let j = i+1; j < arr.length; j++) {
if(S == arr[i] + arr[j]) sum.push([arr[i],arr[j]])
}
}
return sum
}
Brute Force not best way to solve but it works.
Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)
((arr,targetSum) => {
if ((arr && arr.length === 0) || targetSum === undefined) {
return false;
} else {
for (let x = 0; x <=arr.length -1; x++) {
let partnerInPair = targetSum - arr[x];
let start = x+1;
let end = (arr.length) - 2;
while(start <= end) {
let mid = parseInt(((start + end)/2));
if (arr[mid] === partnerInPair) {
console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
break;
} else if(partnerInPair < arr[mid]) {
end = mid - 1;
} else if(partnerInPair > arr[mid]) {
start = mid + 1;
}
}
};
};
})([0,1,2,3,4,5,6,7,8,9], 10)
function twoSum(arr, target) {
let res = [];
let indexes = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (target === arr[i] + arr[j] && !indexes.includes(i) && !indexes.includes(j)) {
res.push([arr[i], arr[j]]);
indexes.push(i);
indexes.push(j);
}
}
}
return res;
}
console.log('Result - ',
twoSum([1,2,3,4,5,6,6,6,6,6,6,6,6,6,7,8,9,10], 12)
);
Brute force.
const findTwoNum = ((arr, value) => {
let result = [];
for(let i= 0; i< arr.length-1; i++) {
if(arr[i] > value) {
continue;
}
if(arr.includes(value-arr[i])) {
result.push(arr[i]);
result.push(value-arr[i]);
break;;
}
}
return result;
});
let arr = [20,10,40,50,60,70,30];
const value = 120;
console.log(findTwoNum(arr, value));
OUTPUT : Array [50, 70]
function twoSum(arr){
let constant = 17;
for(let i=0;i<arr.length-2;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i]+arr[j] === constant){
console.log(arr[i],arr[j]);
}
}
}
}
let myArr = [2, 4, 3, 5, 7, 8, 9];
function getPair(arr, targetNum) {
for (let i = 0; i < arr.length; i++) {
let cNum = arr[i]; //my current number
for (let j = i; j < arr.length; j++) {
if (cNum !== arr[j] && cNum + arr[j] === targetNum) {
let pair = {};
pair.key1 = cNum;
pair.key2 = arr[j];
console.log(pair);
}
}
}
}
getPair(myArr, 7)
let sumArray = (arr,target) => {
let ar = []
arr.forEach((element,index) => {
console.log(index);
arr.forEach((element2, index2) => {
if( (index2 > index) && (element + element2 == target)){
ar.push({element, element2})
}
});
});
return ar
}
console.log(sumArray([8, 7, 2, 5, 3, 1],10))
Use {} hash object for storing and fast lookups.
Use simple for loop so you can return as soon as you find the right combo; array methods like .forEach() have to finish iterating no matter what.
And make sure you handle edges cases like this: twoSum([1,2,3,4], 8)---that should return undefined, but if you don't check for !== i (see below), you would erroneously return [4,4]. Think about why that is...
function twoSum(nums, target) {
const lookup = {};
for (let i = 0; i < nums.length; i++) {
const n = nums[i];
if (lookup[n] === undefined) {//lookup n; seen it before?
lookup[n] = i; //no, so add to dictionary with index as value
}
//seen target - n before? if so, is it different than n?
if (lookup[target - n] !== undefined && lookup[target - n] !== i) {
return [target - n, n];//yep, so we return our answer!
}
}
return undefined;//didn't find anything, so return undefined
}
We can fix this with simple JS object as well.
const twoSum = (arr, num) => {
let obj = {};
let res = [];
arr.map(item => {
let com = num - item;
if (obj[com]) {
res.push([obj[com], item]);
} else {
obj[item] = item;
}
});
return res;
};
console.log(twoSum([2, 3, 2, 5, 4, 9, 6, 8, 8, 7], 10));
// Output: [ [ 4, 6 ], [ 2, 8 ], [ 2, 8 ], [ 3, 7 ] ]
Solution In Java
Solution 1
public static int[] twoNumberSum(int[] array, int targetSum) {
for(int i=0;i<array.length;i++){
int first=array[i];
for(int j=i+1;j<array.length;j++){
int second=array[j];
if(first+second==targetSum){
return new int[]{first,second};
}
}
}
return new int[0];
}
Solution 2
public static int[] twoNumberSum(int[] array, int targetSum) {
Set<Integer> nums=new HashSet<Integer>();
for(int num:array){
int pmatch=targetSum-num;
if(nums.contains(pmatch)){
return new int[]{pmatch,num};
}else{
nums.add(num);
}
}
return new int[0];
}
Solution 3
public static int[] twoNumberSum(int[] array, int targetSum) {
Arrays.sort(array);
int left=0;
int right=array.length-1;
while(left<right){
int currentSum=array[left]+array[right];
if(currentSum==targetSum){
return new int[]{array[left],array[right]};
}else if(currentSum<targetSum){
left++;
}else if(currentSum>targetSum){
right--;
}
}
return new int[0];
}
function findPairOfNumbers(arr, targetSum) {
var low = 0, high = arr.length - 1, sum, result = [];
while(low < high) {
sum = arr[low] + arr[high];
if(sum < targetSum)
low++;
else if(sum > targetSum)
high--;
else if(sum === targetSum) {
result.push({val1: arr[low], val2: arr[high]});
high--;
}
}
return (result || false);
}
var pairs = findPairOfNumbers([1,2,3,4,4,5], 8);
if(pairs.length) {
console.log(pairs);
} else {
console.log("No pair of numbers found that sums to " + 8);
}
Simple Solution would be in javascript is:
var arr = [7,5,10,-5,9,14,45,77,5,3];
var arrLen = arr.length;
var sum = 15;
function findSumOfArrayInGiven (arr, arrLen, sum){
var left = 0;
var right = arrLen - 1;
// Sort Array in Ascending Order
arr = arr.sort(function(a, b) {
return a - b;
})
// Iterate Over
while(left < right){
if(arr[left] + arr[right] === sum){
return {
res : true,
matchNum: arr[left] + ' + ' + arr[right]
};
}else if(arr[left] + arr[right] < sum){
left++;
}else{
right--;
}
}
return 0;
}
var resp = findSumOfArrayInGiven (arr, arrLen, sum);
// Display Desired output
if(resp.res === true){
console.log('Matching Numbers are: ' + resp.matchNum +' = '+ sum);
}else{
console.log('There are no matching numbers of given sum');
}
Runtime test JSBin: https://jsbin.com/vuhitudebi/edit?js,console
Runtime test JSFiddle: https://jsfiddle.net/arbaazshaikh919/de0amjxt/4/
function sumOfTwo(array, sumNumber) {
for (i of array) {
for (j of array) {
if (i + j === sumNumber) {
console.log([i, j])
}
}
}
}
sumOfTwo([1, 2, 3], 4)
function twoSum(args , total) {
let obj = [];
let a = args.length;
for(let i = 0 ; i < a ; i++){
for(let j = 0; j < a ; j++){
if(args[i] + args[j] == total) {
obj.push([args[i] , args[j]])
}
}
}
console.log(obj)}
twoSum([10,20,10,40,50,60,70,30],60);
/* */

How do I sum all prime numbers?

I am working on an excercise to sum all prime numbers from 2 to the parameter. I have worked this far in the code, but am stuck. I believe by using the splice function, I am actually skipping an element because of a changed indices.
function sumPrimes(num) {
var primearray = [];
var sum = 0;
for(var i =2; i <= num; i++){
primearray.push(i);
}
for(var j = 0; j < primearray.length; j++) {
console.log(primearray[j]);
if ((primearray[j]%2===0) && (primearray[j] >2)) {
primearray.splice(j,1);
} else if ((primearray[j]%3===0) && (primearray[j] > 3)) {
primearray.splice(j,1);
console.log(primearray);
} else if ((primearray[j]%5===0) && (primearray[j] > 5)) {
primearray.splice(j,1);
} else if ((primearray[j]%7===0) && (primearray[j] > 7)) {
primearray.splice(j,1);
}
}
sum = primearray.reduce();
return sum;
}
sumPrimes(30);
I haven't utilized the reduce function yet because I am still working on the if else statements.
I found a pretty good solution to the same problem. afmeva was spot on. This is how it works.
function isPrime(val){
//test if number is prime
for(var i=2; i < val; i++){
if(val % i === 0){
return false;
}
}
return true;
}
In the above code we accept a number to determine whether or not it is prime. We then loop from two all the way up until our number minus one because we know that our number will be divisible by itself and one. If the remainder of our value with the current loop value is zero then we know it is not prime so break out and say so.
This article explains very well
function sumPrimes(num) {
var answer = 0;
//loop through all numbers from 2 to input value
for(var i=2; i <= num; i++){
//sum only prime numbers, skip all others
if(isPrime(i)){
answer += i;
}
}
return answer;
}
sumPrimes(977); // 73156
Here's another good resource
function sumPrimes(num) {
let arr = Array.from({length: num+1}, (v, k) => k).slice(2);
let onlyPrimes = arr.filter( (n) => {
let m = n-1;
while (m > 1 && m >= Math.sqrt(n)) {
if ((n % m) === 0)
return false;
m--;
}
return true;
});
return onlyPrimes.reduce((a,b) => a+b);
}
sumPrimes(977);
I have seen lots of people putting all prime numbers into arrays and in order to check if a number is prime, they check from 2 to the number to see if there's a remainder.
You only need to check odd numbers, and only need to count to half the number because a number can't be divisible by any number greater than it has.
Here's my solution:
function sumPrimes(num){
var sum = num>=2?2:0;
for(var i=3;i<=num;i+=2){
var isPrime=true;
for(var j=3;j<(i/2);j++){
if (i%j==0)
{
isPrime=false;
break;
}
}
sum+=isPrime?i:0;
}
return sum;
}
Note: I started from j=2 because we are only checking odd numbers, so they'd never be divisible by 2.
function sumPrimes(num) {
var sumArr= [];
for(var i=0;i<=num;i++){
if(isPrime(i))
sumArr.push(i);
}
sumArr = sumArr.reduce(function(a,b){
return a+b;
})
return sumArr;
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i === 0)
return false;
}
return true;
}
sumPrimes(10);
something like this?
function isPrime(_num) {
for(var i = 2; i < _num; i++) {
if(!(_num % i)) {
return false
}
}
return true;
}
function sumPrimes(_num) {
var sum = 0;
for(var i = 2; i <= _num; i++) {
if(isPrime(i)) {
sum += i;
}
}
return sum;
}
sumPrimes(20) // 77
sumPrimes(5) // 10
You could do this as well.
function sumPrimes(num) {
var sum = 0;
for (var i = 0; i <= num; i++) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
function isPrime(n) {
if (n < 2) { return false; }
if (n !== Math.round(n)) { return false; }
var result = true;
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
result = false;
}
}
return result;
}
Here's my solution. I hope you find it easy to interpret:
function sumPrimes(num) {
// determine if a number is prime
function isPrime(n) {
if (n === 2) return true;
if (n === 3) return true;
if (n % 2 === 0) return false;
if (n % 3 === 0) return false;
var i = 5;
var w = 2;
while (i * i <= n) {
if (n % i === 0) {
return false;
}
i += w;
w = 6 - w;
}
return true;
}
// subtract 1 for 'not being prime' in my context
var sum = isPrime(num) ? num - 1 : -1;
for (var x = 0; x < num; x++) {
if (isPrime(x) === true) {
sum += x;
}
}
return sum;
}
here is my solution to sum of n prime number
function sumOfNPrimeNumber(num){
var sum = 0;
const isPrime = function(n){
if (isNaN(n) || !isFinite(n) || n%1 || n<2) {
return false;
}
if (n%2==0){
return (n==2);
}
var sqrt = Math.sqrt(n);
for (var i = 3; i < sqrt; i+=2) {
if(n%i == 0){
return false;
}
}
return true;
}
const getNextPrime = function* (){
let nextNumber = 2;
while(true){
if(isPrime(nextNumber)){
yield nextNumber;
}
++nextNumber;
}
}
const nextPrime = getNextPrime();
for (var i = 0; i < num; i++) {
sum = sum + nextPrime.next().value;
}
return sum;
}
console.log(sumOfNPrimeNumber(3));
All the above answers make use of helper functions or aren't time efficients.
This is a quick, recursive solution in O(n) time:
// # signature int -> int
// # interpr: returns sum of all prime integers <= num
// assume: num is positive integer
function sumPrimes(num) {
if (num <= 2) {
return 2;
}
let i = 2;
while (i < num) {
if (num % i === 0) {
return sumPrimes(num - 1)
}
i++;
}
return num + sumPrimes(num - 1)
}
// test
sumPrimes(10); // -> 17
function prime_sum(num){
let count=0; *//tracks the no of times number is divided perfectly*
for(let i=1;i<=num;i++){ *//from 1 upto the number*
if(num%i==0){count++};
}
if(count===2){return "Prime"};
return{"Not prime"};
}
console.log(prime_sum(10));//expected output is 17**
//the code receives a number,checks through the range and returns prime if it meets the condition
The following solution uses the Eratosthenes Sieve to sum all prime numbers lower than or equal to num. The first for loop fills an array with size equal to num with true. The second for loop sets to false all non-prime numbers in the array. Then, the last for loop simply iterates through the array to sum all the array indexes i for which the value in the array, i.e., array[i], is equal to true.
/**
* Sum all primes lower or equal than n.
* Uses the Eratosthenes Sieve to find all primes under n.
*/
function sumPrimes(num) {
let array = [];
let output = 0;
// Fill an array of boolean with 'true' from 2 to n.
for (let i = 0; i <= num; i++) {
array.push(true);
}
// Set all multiples of primes to 'false' in the array.
for (let i = 2; i <= Math.sqrt(num); i++) {
if (array[i]) {
for (let j = i * i; j <= num; j += i) {
array[j] = false;
}
}
}
// All array[i] set to 'true' are primes, so we just need to add them all.
for (var i = 2; i <= num; i++) {
if (array[i]) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
console.log(sumPrimes(977)); // 73156
console.log(sumPrimes(250_000_000)); // 197558914577
function sumPrimes(num) {
let output = 0;
// check if num is a prime number
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
This is what I've done to get primes. I don't know if it's the most efficient, but it works. This is in Java, but can be easily converted to JavaScript. Hopefully this will help point you in the right direction.
final int TOTAL = 10;
int primes[] = new int[TOTAL];
int arrPos = 2;
boolean prime = false;
primes[0] = 2;
for (int i = 2; i < TOTAL; i++) {
prime = false;
int sqrt = (int) Math.sqrt(i);
for (int j = 1; j < arrPos && primes[j] < sqrt; j++) {
if (i % primes[j] != 0) {
prime = true;
} else {
prime = false;
break;
}
}
if (prime == true) {
primes[arrPos] = i;
arrPos++;
}
}

Categories

Resources