Program to generate primes not working - javascript

I made the following code to generate an array of primes till a number 'num'.
But It is giving totally unexpected results.
I tried debugging it on chrome but the debugger does not help much as it just skips over the 4th line.
function Sieve(num) {
var arr = Array.from({length:num-1}).map((x,i)=> i+2);
var numb = Math.floor(Math.sqrt(num));
var arra = Array.from({length:numb-1}).map((x,i)=> i+2);
arra.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y=!x)));
console.log(arr);
}
Sieve(10)

Is this supposed to be Sieve of Eratosthenes algorithm? Just to mention, you know this is not the fastest way to generate primes?
Bersteins's primegen is confirmed faster, and they might be even faster solutions.
That aside, let's display simple code for what you are trying to achieve:
var eratosthenes = function(n) {
// Eratosthenes algorithm to find all primes under n
var array = [], upperLimit = Math.sqrt(n), output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if(array[i]) {
output.push(i);
}
}
return output;
};
This is far simpler to understand and split in sections.
BTW, you know Array.from(new Array(n-1), (x,i) => i+2); works? There is no need to array.from() and then .map(), you can pass map function directly into from as a parameter. Also with new Array(n) code is a bit more readable.
This is solution using your principles.
function Sieve(num) {
var arra = Array.from(new Array(num-1), (x,i) => i+2);
var comb = Array.from(new Array(Math.sqrt(num)-1), (x,i) => 2+i);
comb.forEach(x => arra=arra.filter(y => (y%x !== 0) || (y===x) ));
console.log(arra);
}
Sieve(100);
It's on CodePen since JSFiddle breaks. labda solution to Erathostene's sieve

Related

Generate non-duplicate random number array JS 2nd [duplicate]

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?
var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}
The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.
Edit
Here's a brief Knuth Shuffle algorithm example:
void shuffle(vector<int> nums)
{
for (int i = nums.size()-1; i >= 0; i--)
{
// this line is really shorthand, but gets the point across, I hope.
swap(nums[i],nums[rand()%i]);
}
}
Try this once:
//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
shuffle = function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
shuffle(testArr);
This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.
var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
{
r = Math.floor(Math.random()*12); // Get a random index
if (tempArray[r] === undefined) // If the index hasn't been used yet
{
document.write(numberArray[r]); // Display it
tempArray[r] = true; // Flag it as have been used
}
else // Otherwise
{
i--; // Try again
}
}
Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.
If I understand you correctly, you want to shuffle your array.
Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).
You can then print the first nine array elements, which will be in random order and not repeat.
Here is a generic way of getting random numbers between min and max without duplicates:
function inArray(arr, el) {
for(var i = 0 ; i < arr.length; i++)
if(arr[i] == el) return true;
return false;
}
function getRandomIntNoDuplicates(min, max, DuplicateArr) {
var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
if (DuplicateArr.length > (max-min) ) return false; // break endless recursion
if(!inArray(DuplicateArr, RandomInt)) {
DuplicateArr.push(RandomInt);
return RandomInt;
}
return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}
call with:
var duplicates =[];
for (var i = 1; i <= 6 ; i++) {
console.log(getRandomIntNoDuplicates(1,10,duplicates));
}
const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
result = nums[Math.floor(Math.random()*nums.length)];
const index = nums.indexOf(result);
nums.splice(index, 1);
console.log(i+' - '+result);
}

How can I optimize this code? Digit N Powers

Problem source
https://www.freecodecamp.org/learn/coding-interview-prep/project-euler/problem-30-digit-n-powers
I am curious as to how I can optimize this code. The goal of the code is to find a sum of all numbers whose digits, when raised to the power n, add to the source number.
```
function digitnPowers(n) {
let newArr = [];
let total = 0;
for (let i = 2; i <= Math.pow(9, n) * n; i++) {
let product = 0;
let thisVar = i.toString().split("");
console.log(thisVar);
for (let j = 0; j < thisVar.length; j++){
product += Math.pow(thisVar[j], n);
console.log(product);
}
if (product === i) {
newArr.push(i);
}
}
for (let i = 0; i < newArr.length; i++){
total += newArr[i];
console.log(total);
}
return total;
}
```
All of the code, when run, come out with the correct answers:
```
digitnPowers(2); = 0
digitnPowers(3); = 1301
digitnPowers(4); = 19316
digitnPowers(5); = 443839
```
The console logs are only present to help me learn to solve this problem. My first step in optimization would be to remove those.
My concern is that when I run this function with 5, the code needs to loop nearly 300,000 times, and this function with 4, nearly 27,000. If n were 6, it'd require 3.1million loops. As of now, the code works, but slowly. Any ideas?

How to code all for all cases of Two Sum javascript problem

I have been working on the two sum problem for the past few hours and can't seem to account for the case where there are only two numbers and their sum is the same as the first number doubled.
The result should be [0,1], but i'm getting [0,0].
let nums = [3,3];
let targetNum = 6;
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let b = i+1; b < nums.length; b++) {
if ((nums[i] + nums[b]) == target) {
return [nums.indexOf(nums[i]), nums.indexOf(nums[b])];
}
}
}
}
console.log(twoSum(nums, targetNum))
Two Sum
My approach uses a javascript object and completes the algorithm in O(n) time complexity.
const twoSum = (nums, target) => {
let hash = {}
for(i=0;i<nums.length;i++) {
if (hash[nums[i]]!==undefined) {
return [hash[nums[i]], i];
}
hash[target-nums[i]] = i;
}
};
console.log(twoSum([2,7,11,15], 9)); // example
This is not the way to solve the problem. Step through the array and save the complement of the target wrt the number in the array. This will also solve your corner case.
You should consider, indexOf(i) -> start from the first element, returns the index when match found! That is why in your code, nums.indexOf(nums[i]) and nums.indexOf(nums[b]) which is basically 3 in all two cases, it will return 0, cause 3 is the first element in array.
instead of doing this, return the index itself.
let nums = [3,3];
let targetNum = 6;
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let b = i+1; b < nums.length; b++) {
if ((nums[i] + nums[b]) == target) {
return i + "" +b;
}
}
}
}
console.log(twoSum(nums, targetNum))

Leetcode: Remove duplicates from sorted array (Javascript)

Why does my solution work in the console but not on leetcode?
var removeDuplicates = function(nums) {
let res = [];
for(let num of nums) {
if(res.includes(num) === false) {
res.push(num);
}
}
return res.length;
};
Console:
screenshot
Leetcode:
let arr = [1, 1, 2]
removeDuplicates(arr) // 3
You can try changing includes to indexOf, may be includes is not working in your environment. Also, instead of returning length you should return res.
Just in case you want to try another approach, you can look at Sets like below
var removeDuplicates = function(nums) {
return [...new Set(nums)]
};
console.log(removeDuplicates([1,1,2]))
console.log(removeDuplicates([1,1,2,3]))
You don't use sortness properly. Algorithmically it is more effective to compare item with previous one, so complexity is O(N).
Perhaps JS has some high-order function like Python groupby to make shorter code, but described method is definitely the best possible from algorithmical point of view.
ideone
var removeDuplicates = function(nums) {
let res = [];
let last = NaN
for(i=0; i<nums.length; i++) {
if(nums[i] != last) {
res.push(nums[i]);
last = nums[i];
}
}
return res.length;
};
let arr = [1, 1, 2]
print(removeDuplicates(arr))
>>2
Here is another solution you can try...
var removeDuplicates = function(nums) {
let p1 = 0,lastVal =nums[0] -1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] != lastVal) {
nums[p1] = nums[i];
lastVal = nums[i]
p1 +=1;
}
}
nums.length = p1;
console.log(nums);
};
let arr = [1, 1, 2]
removeDuplicates(arr);
Click here to RUN

Random number generator without dupes in Javascript?

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?
var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}
The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.
Edit
Here's a brief Knuth Shuffle algorithm example:
void shuffle(vector<int> nums)
{
for (int i = nums.size()-1; i >= 0; i--)
{
// this line is really shorthand, but gets the point across, I hope.
swap(nums[i],nums[rand()%i]);
}
}
Try this once:
//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
shuffle = function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
shuffle(testArr);
This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.
var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
{
r = Math.floor(Math.random()*12); // Get a random index
if (tempArray[r] === undefined) // If the index hasn't been used yet
{
document.write(numberArray[r]); // Display it
tempArray[r] = true; // Flag it as have been used
}
else // Otherwise
{
i--; // Try again
}
}
Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.
If I understand you correctly, you want to shuffle your array.
Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).
You can then print the first nine array elements, which will be in random order and not repeat.
Here is a generic way of getting random numbers between min and max without duplicates:
function inArray(arr, el) {
for(var i = 0 ; i < arr.length; i++)
if(arr[i] == el) return true;
return false;
}
function getRandomIntNoDuplicates(min, max, DuplicateArr) {
var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
if (DuplicateArr.length > (max-min) ) return false; // break endless recursion
if(!inArray(DuplicateArr, RandomInt)) {
DuplicateArr.push(RandomInt);
return RandomInt;
}
return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}
call with:
var duplicates =[];
for (var i = 1; i <= 6 ; i++) {
console.log(getRandomIntNoDuplicates(1,10,duplicates));
}
const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
result = nums[Math.floor(Math.random()*nums.length)];
const index = nums.indexOf(result);
nums.splice(index, 1);
console.log(i+' - '+result);
}

Categories

Resources