How to add 5 random numbers which are less than 10? - javascript

I've created two functions. One to create 5 random numbers to push them into an array. And another one to sum up the numbers. The random number generator is working and making an array perfectly. But the sum is not accurate. I'm unable to find where the problem is.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(sumNum(arr));

Because you are logging a different set of array values and checking the sum of different set of array values.
I have changed your console.log statement.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(arr);
console.log(sumNum(arr));

You are not performing the sum on the array that you logged in the console. What you are logging is
console.log(pushIntoArray()); // This is displayed in the console
But then you are generating a ney array by calling
let arr = pushIntoArray();
BUT you are performing the sum on the arr array not the one that is displayed in the console.
console.log(sumNum(arr)); // you did not console.log(arr)
The function works correctly, you are just calling it on the wrong thing.

the function is working correctly but you are logging a different array of random numbers and calculating the sum of a different array.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
// this array is different (this is not passed to the sumNum function)
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// this array is different
let arr = pushIntoArray();
console.log("sum of array:", arr)
console.log(sumNum(arr));

Related

combinational sum- how to write test correctly JavaScript

I need to test Combinational Sum I algorithm using JavaScript. I have done all things in html, but I don't know how to call function (in script.js), which contain Combinational Sum I algorithm, correctly. Does anybody know how to call it? how to calculate? how to write test?
let botun=document.getElementById('botun');
//including variables
botun.onclick=function(){
let niz=document.getElementById('input').value;
let target=document.getElementById('target').value;
//convert string in array
let nizInt=niz.split(' ').map(Number);
//convert element of array in Int
let nizIntNovi=[];
for(var i=0; i<nizInt.length; i++) {
nizInt[i] = parseInt(nizInt[i], 10);
nizIntNovi[i]=nizInt[i];
}
console.log(nizIntNovi);
//calling function
let meduRez=combinationalSum(nizIntNovi,target);
console.log(meduRez);
}
// Javascript program to find all combinations that
// sum to a given value
var combinationalSum=function(candidates,target){
//global result
const result=[];
candidates.sort((a,b)=>a-b);
//dfs recursive helper
const dfs=(i,candidates,target,slate)=>{
//backtracking case
if(target<0) return;
//base case
if(target===0){
result.push(slate.slice());
return;
}
//dfs recursive case
for(let j=i;j<candidates.lenght;j++){
slate.push(candidates[j]);
dfs(j,candidates,target-candidates[j],slate);
slate.pop();
}
}
dfs(0,candidates,target,[]);
return result;
};
You call it like in the snippet below, with some basic HTML.
Or using the console of the browser.
The function is not working right.
You can read about implementation here https://www.geeksforgeeks.org/combinational-sum/
let botun = document.getElementById('botun');
//including variables
botun.onclick = function() {
let niz = document.getElementById('input').value;
let target = document.getElementById('target').value;
//convert string in array
let nizInt = niz.split(' ').map(Number);
//convert element of array in Int
let nizIntNovi = [];
for (var i = 0; i < nizInt.length; i++) {
nizInt[i] = parseInt(nizInt[i], 10);
nizIntNovi[i] = nizInt[i];
}
console.log(nizIntNovi);
//calling function
let meduRez = combinationalSum(nizIntNovi, target);
console.log(meduRez);
}
// Javascript program to find all combinations that
// sum to a given value
var combinationalSum = function(candidates, target) {
//global result
const result = [];
candidates.sort((a, b) => a - b);
//dfs recursive helper
const dfs = (i, candidates, target, slate) => {
//backtracking case
if (target < 0) return;
//base case
if (target === 0) {
result.push(slate.slice());
return;
}
//dfs recursive case
for (let j = i; j < candidates.lenght; j++) {
slate.push(candidates[j]);
dfs(j, candidates, target - candidates[j], slate);
slate.pop();
}
}
dfs(0, candidates, target, []);
return result;
};
input {
height: 30px;
width: 100px;
line-height: 1;
}
.as-console-wrapper {
max-height: 100% !important;
}
Input: <input id="input" value="1 2 3 4"> Target: <input id="target" value="6">
<input type="button" id="botun" value="click">
There is solved problem. Task: input array of integer, input target then calculate Combinational Sum and print the smallest array of Combinational Sum.
For example: Input: [2,4,6] Target:4. Output will be 1, because Combinational Sum prints (2+2),(4). Smaller array is 4 and it contains one element so 1 will be output!
Code:
let botun=document.getElementById('botun');
let nizSplitNew=[];
let targetNew;
let brojac;
let array=[];
let min;
var rezultat=document.getElementById("rezl");
//including variables
botun.onclick=function(){
let niz=document.getElementById('input').value;
let target=document.getElementById('target').value;
//convert string in array
let nizSplit=niz.split(',').map(Number);
//convert element of array in Int
for(var i=0; i<nizSplit.length; i++) {
nizSplitNew[i] = parseInt(nizSplit[i], 10);
}
console.log(nizSplitNew);
targetNew = parseInt(target, 10);
//calling function
let meduRez=combinationSum(nizSplitNew,targetNew);
// Javascript program to find all combinations that
// sum to a given value
function combinationSum(arr, sum) {
let ans = new Array();
let temp = new Array();
// first do hashing since hashset does not always
// sort
// removing the duplicates using HashSet and
// Sorting the arrayList
let set = new Set([...arr]);
arr = [...set];
arr.sort()
findNumbers(ans, arr, sum, 0, temp);
return ans;
}
function findNumbers(ans, arr, sum, index, temp) {
if (sum == 0) {
// pushing deep copy of list to ans
ans.push([...temp]);
return;
}
for (let i = index; i < arr.length; i++) {
// checking that sum does not become negative
if ((sum - arr[i]) >= 0) {
// pushing element which can contribute to
// sum
temp.push(arr[i]);
findNumbers(ans, arr, sum - arr[i], i, temp);
// removing element from list (backtracking)
temp.splice(temp.indexOf(arr[i]), 1);
}
}
}
// Driver Code
// arr.push(5);
// arr.push(4);
// arr.push(8);
//let arr = []
for(let i=0;i<nizSplitNew;i++){
nizSplitNew.push(nizSplitNew[i]);
}
let sum = targetNew;
let ans = combinationSum(nizSplitNew, sum);
// If result is empty, then
// print all combinations stored in ans
for (let i = 0; i < ans.length; i++) {
brojac=0;
for (let j = 0; j < ans[i].length; j++) {
brojac=brojac+1;
}
array.push(brojac);
}
console.log(array);
min = Math.min(...array);
if (array.length == 0) {
rezultat.innerHTML=`<p>-1</p>`
}
else{
rezultat.innerHTML=`<p>${min}</p>`
}
}

RangeError: Maximum call stack size exceeded at Math.random (<anonymous>)

I tried to take the last ten lotteries numbers and try to combine them to 14 random guesses.
What I did is to define 2 arrays, one with the all numbers and one with the strong number.
With that, I want to generate 14 combine guesses but when I my loop is more than 4 I got an error with the title above.
Can someone explain me what is my problem ? Thanks :]
Code:
const paisRsultsNumbers = [
2,15,19,33,34,36,1,2,13,14,22,36,3,5,13,23,24,35,1,3,4,13,20,37,2,6,10,11,16,35,2,5,6,7,15,30,2,7,8,10,30,31,5,13,15,21,22,33,3,5,7,9,19,27,1,7,16,23,28,34
]
const paisResultsStrongNumber = [
7,7,1,5,6,7,1,7,5,5
]
const guesses = [];
const gen_nums = [];
function getRandSixNumbers(){
let nums = [];
for(let i = 0; i < 6; i++) {
nums.push(getRandNum(paisRsultsNumbers));
}
return nums;
}
getRandSixNumbers()
function getRandStrongNumber(){
return paisResultsStrongNumber[Math.floor(Math.random() * paisResultsStrongNumber.length)]
}
function isInArray(array, el) {
for(let i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function getRandNum(array) {
let rand = array[Math.floor(Math.random()*array.length)];
if(!isInArray(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return getRandNum(array);
}
(function createGuess(){
for(let i = 0; i < 14; i++){
guesses.push({
six: [getRandSixNumbers()],
strongNumber: getRandStrongNumber()
})
}
console.log(guesses)
})()
function getRandNum(array) {
let rand = array[Math.floor(Math.random()*array.length)];
if(!isInArray(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return getRandNum(array);
}
getRandStrongNumber tries to pick a random unique number among paisRsultsNumbers array. It's fine when you try less than the total unique numbers. But when you exceed that your getRandStrongNumber function will keep calling itself endlessly. And 6*14 will exceed that number for sure.
Edit:
You can reset the gen_nums array after you pick the 6 unique random numbers in your loop.
let gen_nums = [];
for(let i = 0; i < 14; i++){
guesses.push({
six: [getRandSixNumbers()],
strongNumber: getRandStrongNumber()
})
gen_nums = []
}

how to get maximum sub array in javascript

var maxSubArray = function(nums) {
let sum = 0,
result = 0;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
let nums = [-2,1,-3,4,-1,2,1,-5,4];
console.log(maxSubArray(nums));
Question
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
But my test case fail
Input
[-1]
Output
0
Expected
-1
and one more test case fails
Input
[-2,-1]
Output
0
Expected
-1
Answer
var maxSubArray = function(nums) {
let sum = 0,
result = 0,
max=nums[0];
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
if(nums[i] > max){
max = nums[i];
}
}
return result <=0 ? max :result ;
};
Your result should start at -Infinity (or at the value of the first item of the array), otherwise an array containing all negative numbers won't give a proper result. The calculation of sum inside the loop should also use Math.max(nums[i], sum + nums[i]);, otherwise if you pass 0 to Math.max, the current running total will always be at least 0, resulting in an incorrect answer when the passed array contains all negative values.
var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);
var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);
<!-- begin snippet: js hide: false console: true babel: false -->

how to fix the function to check the same random array value

I am learning javascript, I have been able to create a function that has a parameter, the function has the task of forming an array containing a 2 character (0/1) random string of 1 parameter and the return value must be an array.
example:
console.log (generateString(2));
sample results:
['01', '11']
The problem I face is even though it's a random string, but it still has the possibility to have the same value. Suppose I run the program code
console.log (generateString(4));
and one of the results is like this:
['00', '00', '01', '10']
my question is how can I ensure that the return value of the array has no duplicate value? This is my code so far..
function generateString(num){
let newArray = [];
for(let i = 0; i < num; i++){
let randomChar = generateCharacters();
if(i >= 1 && (newArray[i - 1] === randomChar)){
randomChar = generateCharacters();
newArray.push(randomChar);
} else {
newArray.push(randomChar);
}
}
return newArray;
}
function generateCharacters(){
const chars = '01';
let result = '';
for (let j = 2; j > 0; --j){
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
console.log(generateString(4));
Just check for the duplicate before adding the new string.
function generateString(num){
let newArray = [];
let i =0;
while(i<num){
console.log(newArray)
let randomChar = generateCharacters();
if(newArray.indexOf(randomChar)<=-1){
newArray.push(randomChar);
i+=1;
}
}
return newArray;
}
You can use a do-while inside the for-loop and keep making new random strings until the new strings generated is not included in the previous array.
function generateString(num){
let newArray = [];
let randomChar;
for(let i = 0; i < num; i++){
do{
randomChar = generateCharacters();
}
while(newArray.includes(randomChar));
newArray.push(randomChar)
}
return newArray;
}
function generateCharacters(){
const chars = '01';
let result = '';
for (let j = 2; j > 0; --j){
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
console.log(generateString(4));
You can shuffle the array of all 4 possible pairs of digits:
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
function generateString(num){
let all = ["00", "01", "10", "11"];
shuffle(all);
return all.slice(0, num); // Only take the number of elements requested
}
console.log(generateString(4));
Made changes in your generateString function. You can use set for not updating duplicates in the result. I think you need to update generateCharacters function to generate all possible strings properly.
function generateString(num){
let newArraySet = new Set();
for(let i = 0; i < num; i++){
let randomChar = generateCharacters();
while(newArraySet.has(randomChar)) {
randomChar = generateCharacters();
}
newArraySet.add(randomChar);
}
return Array.from(newArraySet);
}
function generateCharacters(){
const chars = '01';
let result = '';
for (let j = 2; j > 0; --j){
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
console.log(generateString(4));
When building the array you need to check to see if the random number is not already in the array before adding it to the array. This function will return true if you feed it the array in question and your "random" item you need to check.
function isInArray(myArray, arrayItemToCheck)
{
var found = myArray.find(function(arrayItem) {
return arrayItem == arrayItemToCheck;
});
return !!found
}
in your function, you change the line let randomChar = generateCharacters(); to:
let randomChar;
// loops forever until condition is met
while (true) {
randomChar = generateCharacters();
if (!isInArray(newArray, randomChar)) {
break;
}
}

Make an array filled with numbers 1 to 10000 and then sum all of those numbers [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 6 years ago.
How can I turn this into a function that takes an array of any length and gives you the total?
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for(var i = 0; i < points.length; i++) {
console.log(points[i]);
}
You could do it in two loops, but you might as well just do one loop that does both tasks.
var array = [],
sum = 0;
for (var i = 1; i <= 10000; i++) {
array[i-1] = i;
sum += i;
}
If you want to generalize the task of finding the sum of an array, you can use a function like so:
function arraySum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++)
sum += array[i];
return sum;
}
For those who can understand it though, using reduce is a best answer:
function arraySum(array) {
return array.reduce(function(a,b){return a+b}, 0);
}
You can do get the sum using the for loop itself simply by using a variable
var points = new Array(100),
sum = 0;
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}
for (var i = 0; i < points.length; i++) {
sum += points[i];
}
console.log(sum);
You can reduce these two operations using fill() and forEach() to generate the array and reduce() to get the sum
var points = new Array(10000); // create an array of size 10000
points.fill(1); // fill it with 1 which helps ti=o iterate using foreach
points.forEach(function(v, i) { // iterate the array, you can also use simple for loop here
points[i] = v + i; // update the value
});
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Using for loop and reduce()
var points = []; // initialize an array
for (var i = 1; i <= 10000; i++) {
points.push(i);
}
var sum = points.reduce(function(a, b) { // find sum
return a + b;
});
console.log(sum);
Also you can do the addition and array creation in single for loop
var points = [], // initialize an array
sum = 0;
for (var i = 1; i <= 10000; i++) {
points.push(i); // pushing value to array
sum += i; // summation
}
console.log(sum, points);
var result = 0;
for(var i = 0; i < points.length; i++) {
result += points[i];
}
Function that takes an array of any length and returns the sum:
function sumArray(arrayToSum){
var result = 0;
for(var i = 0; i < arrayToSum.length; i++) {
result += points[i];
}
return result;
}
function arraysum(arraylength) {
var arraysum = 0;
var array1 = new Array();
for(i=1; i<=arraylength; i++) {
array1.push(i);
}
for(i = 0; i< array1.length; i++) {
arraysum += array1[i];
}
return arraysum;
}
Now when you call the function
arraysum(x)
pass the function some variable or integer for example 1, 15, or 10000.
A very elegant and compact solution is to use reduce. It accumulates the array values to reduce it to a single value by applying each value and a start value to a given function, whose return value is used as the start value for the next iteration:
function sum (a, b) {
return a + b;
}
console.log(points.reduce(sum, 0));
If you need to support older browser (e.g. IE 8) you can use a Polyfill.
If you need to create the list of numbers as well, you can create it with
var points = Array.apply(0, Array(10000))
.map(function (current, index) {
return index + 1;
});
It creates an array of 10000 elements and assigns each element it's index + 1.

Categories