Two chunks of code work separately but not together, where do i err? - javascript

Why is it that the following works fine:
var howMany = prompt("How many numbers?");
var myArray = [];
for(var i = 0; i < howMany; i++){
myArray.push(prompt("Enter a number"));
}
alert(myArray);
The code above is intended to ask user how many numbers are they going to put into an array, and it displays the array.
This chunks of code below seems to be fine too.
There is a provided array.
Then the code checks whether the numbers are actually numbers.
After that it adds all the numbers together.
var myArray = [1,2,3,4,5];
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i=0; i<length; i++){
if(typeof array[i]!== typeof first){
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true){
add(myArray);
} else {
console.log("cant do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i=0; i<length; i++){
f+= array[i];
}
alert("The result of addition of this set: " + myArray + " is: " + f);
}
but when i combine the two it does not work. It does not add the numbers.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(prompt("Enter a number"));
}
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i = 0; i < length; i++) {
if (typeof array[i] !== typeof first) {
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
Can you be so kind to correct me?

The return value from prompt is a string, not a number.
var n = prompt("Enter a number");
alert("typeof(n) = " + typeof(n));
Even if you enter a numeric value, the code above will display "typeof(n) = string".
You must convert the string into a number.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"), 10));
}

The prompt function saves strings, so the problem here is that you are trying to make a sum of strings. Just add a typecast in the add function and the script will work correctly:
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += parseInt(array[i]);
}
}

var howMany = prompt("How many numbers?"),
myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"),10));
}
function isDataUniform(array) {
for (i = 0; i < array.length; i++) {
if (typeof array[i] !== "number") {
return false;
}
}
return true;
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}

Related

Fixing Fibonacci sequence script (javascript)

I am trying to write a script that will create numbers in Fibonacci order, I don't understand why this is not working.
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{output.push(1);
console.log(output);}
}
}
In your original code your n never changes as you only assigned it on start.
var output = [];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
var n = output.length;
var nextNum = output[n-1] + output[n-2];
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{
output.push(1);
console.log(output);
}
}
}
fibo(10)
In Javascript numbers are passed by value not reference so they are not the same object in memory. So when the array length changes your n value stays at 0 because they are not the same object.
function fibo(numQuantity) {
let output = [0, 1];
if(numQuantity < 2) {
return output.slice(0, numQuantity);
}
for(let i = 2; i < numQuantity ; i++) {
const n = output.length
output.push(output[n - 1] + output[n - 2])
}
return output;
}
console.log(fibo(1))
console.log(fibo(2))
console.log(fibo(3))
console.log(fibo(4))
Check this fiddle: https://jsfiddle.net/37a4burz/
You need to add n++ to end of your code and change end condition.
Here is full code:
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<= numQuantity ; i++)
{
if (n==0) {
output.push(0);
console.log(output);
}
else if (n==1) {
output.push(1);
console.log(output);
}
else if (n>1) {
output.push(output[n-1] + output[n-2]);
console.log(output);
}
n++;
}
}
fibo(7);

Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

how to get distinct value from an array javascript

how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232

Find the number of subarrays in an array which has the given sum

Here is the problem: Find the number of subarrays in an array, which has the given sum.
this program enter 2 parameters number array and sum.
for example:
subArrayCnt([1,2,3,2,1,8,-3],5)
and the output should be number of subarrays accoding to given sum.
(output should be 3 for above example {2,3}, {3,2}, {8,-3} (number of subarrays))
I tried to do that but there is a problem with it isn't fulfilling the requirment of "The answer should be valid for any given input"
Here is my code:
function subArrayCnt(arr, sum) {
for (var i = 0; i < arr.length; i++) {
var str = [];
var csum= 0;
var output = 0;
for (var j = i; j < arr.length; j++) {
csum+= arr[j];
str.push(arr[j]);
if (csum== sum) {
return(str[i]);
}
}
}
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
this program provide number of subarrays but it isn't fulfilling the requirment of "The answer should be valid for any given input" where should be corrected? any suggetions please.
The other answers seem to be ignoring the fact that the sum can be obtained from any number of elements of the array. Recursion is the best approach here.
function subArrayCnt(arr, sum){
return subArrayRecurse(arr, sum, 0, [], 0)
}
function subArrayRecurse(arr, sum, currentSum, curArray, i){
var count = 0;
//check the current index
var newSum = currentSum + arr[i];
var newSubArray = curArray.concat([arr[i]]);
if(newSum == sum) {
console.log('found another: ' + newSubArray);
count++;
}
if(i + 1 < arr.length) {
//try including the current in further sums
count += subArrayRecurse(arr, sum, newSum, newSubArray, i + 1);
//try not including the current in further sums
count += subArrayRecurse(arr, sum, currentSum, curArray, i + 1);
}
return count;
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
// 8
The 8 combos from the above example are:
1,2,3,2,-3
1,2,2
1,3,1
2,3
2,3,2,1,-3
2,2,1
3,2
8,-3
From your example, I assumed that the sum of two consecutive elements should be the sum to qualify.
function subArrayCnt(arr, sum) {
let outputArr = [];
for(var i=0; i<arr.length; i++){
if(arr[i]+arr[i+1]==sum){
let obj = {l:arr[i],r:arr[i+1]};
outputArr.push(obj);
}
};
return outputArr.length;
};
Try this approach:
function subArrayCnt(arr, sum){
var count = 0;
for(var i = 0; i < arr.length-1; i++){
for(var n = i+1; n < arr.length; n++){
if(arr[i] + arr[n] == sum){
count++;
}
}
}
return count;
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
// 3
You can do that using nested loop. This will get all the possible adjacent sums and then you can compare that sum with the given sum and increase count.
function func(arr,sum){
if(!Array.isArray(arr)) return 0;
let count = 0;
let cur = 0;
for(let i = 0;i<arr.length-1;i++){
cur = arr[i];
for(let j = i+1;j<arr.length;j++){
cur += arr[j];
if(cur === sum){
count++;
break;
}
if(cur > sum) break;
}
}
return count+'';
}
console.log(func([1,2,3,2,1,8,-3],5)) //3
console.log(func([1,2,3,4],10)) //1
Try this:
<script>
function subArray(arr,sum)
{
var subArray=new Array();
count=0;
for(var i=0;i<arr.length;i++)
{
if(arr[i]+arr[i+1]==sum)
{
subArray[count]=[arr[i],arr[i+1]]
count++;
}
}
return subArray;
}
console.log(subArray([1,2,3,2,1,8,-3],5));
</script>
Try this:
I wrote this function. It fulfill the requirement of "The answer should be valid for any given input".
function getSubArrayCount(arr, sum){
if(!Array.isArray(arr)) return 0;
var len = arr.length;
var count = 0;
for(var i = 0; i < len; i++){
var n = 0;
for(var j = i; j < len; j++){
n += arr[j];
if(n === sum) {
count++;
break;
}
}
}
return count;
}
getSubArrayCount([1,2,3,2,1,8,-3],5);

Generate chunks from string

before going to problem, i want to generate dynamically like
temp = word[i] for 2,
temp = word[i-1] + word [i] for 3,
temp = word[i-2] + word[i-1] + word [i] for 4
I explained with code and what i have tried
function produceTwoChArray(word) {
var temp = "";
var tempArr = [];
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === 2) {
tempArr.push(temp);
}
temp = word[i];
}
return tempArr;
}
produceTwoChArray("breaking")
above code will produce result as :
["br", "re", "ea", "ak", "ki", "in", "ng"]
So inside the for loop if i change to below codes to produce three letters then
if (temp.length === 3) {
tempArr.push(temp);
}
temp = word[i-1] + word[i];
Result:
["bre", "rea", "eak", "aki", "kin", "ing"]
so adding word[i-1], word[i-2] with temp length 3, 4 and so on..
For dynamically creating the temp statement, i created these Function
1)
function generateWordSequence(n) {
var n = n - 2;
var temp1 = [];
for (var j = n; j >= 0; j--) {
temp1.push("word[i - " + j + "]");
}
temp1 = temp1.join('+').toString();
return temp1;
}
2)
function generateWordSequence(n, word) {
var n = n - 2;
var temp1 = "";
for (var j = n; j >= 0; j--) {
temp1 = temp1 + word[i - j];
}
return temp1;
}
But both above try's are returning as string so it didnt work. When i invoke above fn in produceTwoChArray fn like this
function produceTwoChArray(word, n) {
var temp = "";
var tempArr = [];
var retVar = generateWordSequence(n, word);
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === n) {
tempArr.push(temp);
}
temp = retVar;
}
return tempArr;
}
When i tried those all logic inside produceTwochArray itself , i also didnt work.
Please help me out here.
You could take a double slice with mapping part strings.
function part(string, count) {
return [...string.slice(count - 1)].map((_, i) => string.slice(i, i + count));
}
console.log(part("breaking", 2));
console.log(part("breaking", 3));
console.log(part("breaking", 4));
You can use slice method in order to obtain a more easy solution.
function produceArray(str,n){
return str=str.split('').map(function(item,i,str){
return str.slice(i,i+n).join('');
}).filter(a => a.length == n);
}
console.log(produceArray("breaking",2));
console.log(produceArray("breaking",3));
console.log(produceArray("breaking",4));
console.log(produceArray("breaking",5));
console.log(produceArray("breaking",6));

Categories