So I mede the prime number generator in JavaScript:
function prime(from, to) {
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
console.log([i]);
}
}
}
prime(2, 9999);
But the output looks like this...
[2]
[3]
[5]
[7]
[11]
...
...and I want it to look like this:
[2,3,5,7,11...]
can someone help me?
thanks for your ideas;-)
function prime(from, to) {
var result = []; // creating a variable for accumulating
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
// console.log([i]);
result.push(i); // adding value
}
}
console.log(result) // console.log result
return result // returning for further usage
}
var a = prime(2, 9999); // put result into a variable
console.log(a); // console.log again for example
You're logging inside your loop. instead, push the results into an array, and just log the array at the end
function prime(from, to) {
var primearray = [];
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
primearray.push(i);
}
}
console.log(primearray)
}
prime(2, 9999);
That's because you are logging each element separately. If you would like to have the output as an array - you can create an empty array and .push() elements to it.
See the example below.
function prime(from, to) {
let primeArray = [];
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
primeArray.push([i]);
}
}
console.log(primeArray)
}
prime(2, 9999);
Cheers.
You can just add numbers to array:
function prime(from, to) {
var arr = [];
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
arr.push(i);
}
if(i === to) {
return arr;
}
}
}
console.log(prime(2, 10));
Try this below:
function prime(from, to) {
let output = []
for (var i = from; i <= to; i++) {
var IsPrime = false;
for (var j = from; j < i; j++) {
if (i % j == 0) {
IsPrime = true;
}
}
if (IsPrime == false) {
output.push([i]);
}
}
print(output)
}
prime(2, 9999);
Related
I'm a new javascript developer from lua and I have some confusion about arrays. I'm trying to build a simple 2d array but after the initialization I keep getting an error that the array is "undefined"
here's the code :
var board = [];
function initBoard(){
for (var i = 0; i < 8; i++){
board.push([]);
for (var j = 0 ;i < 8; i++){
board[j].push([]);
}
}
}
function checkSquare(x, y){
if (typeof(board[x][y]) === ""){
return false;
} else {
return true;
}
}
initBoard();
console.log(checkSquare(3, 3));
Here's the error : Cannot read property '3' of undefined`
You need not only take a look to the loops, but also to the check of the value of an item of the array. The comparison with the result of typeof with an empty string is always false, because there is no data type in Javascript Which is an empty string.
For comparing the value, you could check with the value directly with a Identity/strict equality operator ===. This checks the type of the left and right side and the value as well. For objects, it check if the object has the same reference.
function initBoard() {
var board = [];
for (var i = 0; i < 8; i++) {
board.push([]);
for (var j = 0; j < 8; j++) {
board[i].push('');
}
}
return board;
}
function checkSquare(x, y) {
if (board[x][y] === '') { // check if the item is an empty string
return false;
} else {
return true;
}
}
var board = initBoard();
console.log(checkSquare(3, 3));
There's a little mistale you've made while initialising. You've misplaced j with i. Try this:
var board = [];
function initBoard(){
for (var i = 0; i < 8; i++){
board.push([]);
for (var j = 0 ;j< i; j++){ //There was a mistake here
board[j].push([]);
}
}
}
function checkSquare(x, y){
if (typeof(board[x][y]) === ""){
return false;
} else {
return true;
}
}
initBoard();
console.log(checkSquare(3, 3));
var board = [];
function initBoard(){
for (var i = 0; i < 8; i++){
board.push([]);
for (var j = 0 ;j< i; j++){
board[j].push([]);
}
}
}
function checkSquare(x, y){
if (typeof(board[x][y]) === ""){
return false;
} else {
return true;
}
}
initBoard();
console.log(checkSquare(3, 3));
Two main things, you have a typo in your second loop, it should be based on j not i
and when you are trying to initialize the second array you can't use push because board[j] is undefined and push is a method of an array
var board = [];
function initBoard(){
for (var i = 0; i < 8; i++){
board.push([]);
for (var j = 0 ;j < 8; j++){
board[j] = [];
}
}
}
function checkSquare(x, y){
if (typeof(board[x][y]) === ""){
return false;
} else {
return true;
}
}
initBoard();
console.log(checkSquare(3, 3));
I am attempting to write a javascript file that has a insertion sort function, a function to check a sorted array and return true or false, and an insertion sort function that works from the end of the array index to the beginning.
Here is the code i have
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
}
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} }
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
//function sortCheck(arr) {
//for( var i = 0 ; i < arr.length; i++){
// if(arr[i]>rr[i+1]){
// return false
// }
//}
//return true}
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
The issue I am having right now is that sortedArr is undefined when output with console.log, it appears that the issue is that my function is "undefined" but seeing how i define it above, i dont understand how that is.
Your insertionSort function doesn't return a value, it modifies the array passed as an argument. Instead of var sortedArr = insertionSort(arr), just call insertionSort(arr) and then do console.log(arr).
You have to return arr from the function. It is not returning anything that's why you are getting undefined
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
return arr; }
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} return arr}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
Make sure you return the array from the function(s). Since you currently are not, assigning the function to a variable would not yield any particular value.
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1];
}
arr[j] = val;
}
return arr
}
const myAnagram = (arr1, arr2) => {
let str1 = arr1;
let str2 = arr2;
let temp1 = [];
let temp2 = [];
let flag = 0;
if (str1.length !== str2.length) return "Not Anagram statement A";
for (var i = 0; i < str1.length - 1; i++) {
temp1[i] = str1[i];
}
for (var j = 0; j < str2.length - 1; j++) {
temp2[i] = str2[i];
}
temp1.sort();
temp2.sort();
for (var k = 0; k < str1.length - 1; k++) {
if (temp1[j] !== temp2[j]) return "Not Anagram statement C";
return "Anagram! statement D";
}
}
The problem you have is with the identifiers you have used in loops.
Have a look at the corrected code.
function myAnagram(arr1, arr2) {
var str1 = arr1;
var str2 = arr2;
var temp1 = [];
var temp2 = [];
var flag = 0;
if (str1.length !== str2.length) {
return "Not Anagram statement A";
} else {
for (var i = 0; i < str1.length; i++) {
temp1[i] = str1[i];
}
for (var j = 0; j < str2.length; j++) {
temp2[j] = str2[j];
}
temp1.sort();
temp2.sort();
for (var k = 0; k < str1.length; k++) {
if (temp1[k] !== temp2[k]) {
return "Not Anagram statement C";
} else {
return "Anagram! statement D";
}
}
}
}
Hope it helps !!
PS: You can optimize this code to a great extend.
find two strings are equal size
compare the characters and the count of characters matches
const isAnagram = (str1, str2) => {
const compare = (first, next) => {
return first.split('').sort().join('') === next.split('').sort().join('');
}
return str1.length !== str2.length ? false : compare(str1, str2);
}
Your loops always skip the last elements since you use < together with str1.length - 1. You should either use for (var i = 0; i < str1.length; ++i) {...} or for (var i = 0; i <= str.length-1; ++i) {...}
Furthermore in your comparison loop you already return when the first characters match (or when they don't). Therefore the loop will never compare the second (or nth) characters. The loop should further compare the characters until you are sure the arrays differ at some point.
You can shrink the function like
function isAnagram(str1, str2) {
if (str1.length !== str2.length) return false
var arr1 = arr2 = []
for (var i = 0; i < str1.length; ++i) {
arr1[i] = str1[i]
arr2[i] = str2[i]
}
arr1.sort()
arr2.sort()
for (var i = 0; i < arr1.length; ++i)
if (arr1[i] !== arr2[i]) return false
return true
}
And then
if (isAnagram("frog","rg0f")) {
console.log("Anagram!")
} else {
console.log("Not Anagram.")
}
The function is returning undefined why it's not returning the array length.even at the start of the code it's printing in the console but return is not working.
var resArr = [];
var p;
function persistence(num) {
resArr.push(num);
console.log(resArr);
console.log(resArr.length);
if (num > 10) {
var v = 1;
var x = num.toString();
var arr = [];
for (i = 0; i < x.length; i++) {
arr.push(x.charAt(i));
}
console.log(arr);
for (j = 0; j < arr.length; j++) {
var v = v * arr[j];
}
persistence(v);
} else {
return resArr.length - 1;
}
}
You're not returning in all cases.
Change
persistence(v);
to
return persistence(v);
I need a way to find the 10001th prime number. My code prints out all the prime numbers but I'm not sure how to get the 10001th prime number.
function prime(nth) {
var arr = [2];
var isPrime = true;
for(var i = 3; i <= 100; i++) {
isPrime = true;
for(var j = 2; j < i; j++) {
if(i % j === 0) {
isPrime = false;
break;
}
}
if(isPrime === true) {
arr.push(i);
}
}
return arr;
}
prime();
Use the length of the prime array as the looping condition of your for loop, not the number you're testing.
function prime(nth) {
var arr = [2];
var isPrime = true;
for(var i = 3; arr.length <= nth; i++) {
isPrime = true;
for(var j = 2; j < i; j++) {
if(i % j === 0) {
isPrime = false;
break;
}
}
if(isPrime === true) {
arr.push(i);
}
}
return arr;
}