What is the exactly difference between:
<p id="test"></p>
<script>
function findMax() {
var i;
var max = -Infinity;
for(i=0;i<arguments.length;i++) {
if(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);
</script>
and:
<p id="test"></p>
<script>
function findMax() {
var i = 0;
var max = -Infinity;
for(; i < arguments.length ; i++) {
if(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);
</script>
Maybe I have missed some classes but the first one outputs 163, as it should, while the second one outputs 0. The console says
SyntaxError: return not in function
return max;
Why does the second one return the lowest value, while the first one returns highest value?
while the second one outputs 0.
You didn't initialize i to 0.
Which means i was undefined, and undefined + 1 is NaN.
SyntaxError: return not in function
You missed a curly brace after for-loop, so the return statement went outside the function definition
function findMax() {
var i;
var max = -Infinity;
for(i = 0; i < arguments.length ; i++)
{//this was missed
if(arguments[i] > max)
{
max = arguments[i];
}
}
return max;
}
for the 2nd one you forget the opening bracket { and initial value i=0
You can also simply use Math.max()
in second you are missing a {, try:
function findMax() {
var i;
var max = -Infinity;
for(; i < arguments.length ; i++) {
if(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Related
I am learning selection sort.
I am getting the correct output for some values, but not for all the values, don't know why??
Please find below code snippet:
function selectionSortRecursion(arr,p){
if( arr.length === 1){
return p;
}
min=arr[0];
for(var i =0;i<arr.length;i++){
if (arr[i]<min){
min = arr[i];
var minIdx=i;
}
}
temp=arr[0];
arr[0]=arr[minIdx];
arr[minIdx]=temp;
p.push(arr.shift());
return selectionSortRecursion(arr,p);
}
console.log(selectionSortRecursion([2,3,5,-3,20,0,2,6,-23],[]));
The problem is that the variable minIdx is not declared unless the body of the if statement inside the loop is executed. If the minimum element is at index 0, then arr[i] < min is never true and minIdx is undefined.
To solve it, write var minIdx = 0; before the loop, since min is initialised as the value at index 0. A couple of your other variables should be declared with var, too:
function selectionSortRecursion(arr, p) {
if(arr.length === 0) {
return p;
}
var min = arr[0];
var minIdx = 0;
for(var i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
minIdx = i;
}
}
var temp = arr[0];
arr[0] = arr[minIdx];
arr[minIdx] = temp;
p.push(arr.shift());
return selectionSortRecursion(arr, p);
}
Note that I've also changed the loop variable i to start at 1, since there's no need to compare index 0 with itself; and the base case of the recursion should be when arr.length is 0, not 1, to avoid losing the last element.
I'm trying to return the largest element in the array. With strings this means the longest string. How do I return only the first instance of the largest element.
My code:
function getLongestElement(arr) {
var max = "";
var counter = 0;
for (var i = 0; i < arr.length; i++){
if (arr[i].length > counter) max = arr[i]
}
return max;
}
getLongestElement(['one', 'two', 'three', "thre1"]); // "thre1" not "three".
I'm not quite sure whats wrong with this code. No matter what the largest value is it only returns the last element in the array. Help?
counter is initialized to 0, but you never change its value so the if statement with arr[i].length > counter is always true (unless arr[i].length == 0). To fix it you need to keep track of the largest element of the array inside the loop:
// I renamed counter to maxLength for readability
function getLongestElement(arr) {
var max;
var maxLength = -1;
for (var i = 0; i < arr.length; i++){
if (arr[i].length > maxLength){
maxLength = arr[i].length;
max = i;
}
}
return arr[max];
}
First, good alghoritm should make no assumptions. That means your max shouldn't start from "", but using first array's element. You also don't edit your counter value, that's your main problem. But it is redundant and you can write this function without counter.
function getLongestElement(arr) {
if (arr.length < 1) return /* Some Exception */;
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i].length > max.length) max = arr[i];
}
return max;
}
You forgot to update counter
function getLongestElement(arr) {
var max = "";
var counter = 0;
for (var i = 0; i < arr.length; i++){
if (arr[i].length > counter) {
max = arr[i];
counter = max.length;
}
}
return max;
}
console.log(getLongestElement(['one', 'two', 'three', "thre1"])); // "thre1" not "three".
If you're looking for a pragmatic solution, I'd suggest lodash's _.maxBy:
_.maxBy(['one', 'two', 'three', "thre1"], function(str) {
return str.length;
})
If you're looking for a theoretical solution for the sake of learning,
function getLongestElement(arr) {
var max;
var counter = 0;
for (var i = 0; i < arr.length; i++){
if (arr[i].length > counter) max = arr[i]
counter = Math.max(arr[i].length, counter)
}
return max;
}
The key point here is to make sure you're updating the counter variable to whatever the currently longest length is.
I have defined a function named larger to find the larger number between two arguments (num1, num2). Now I want to use this function inside another function called "largest" which gets an array and return the largest number of that array, but I`ve got stuck. Can anybody help me with that?
Here is my codes:
function larger(num1, num2){
var largerNumber = 0;
if (num1 > num2){
largerNumber = num1;
} else {
largerNumber = num2;
}
return largerNumber;
}
function largest(array){
for (var i = 0; i < array.length ; i++){
for (var j = 0; j < array.length ; j++){
if (array[i] != array[j]){
//I don`t know if I am doing it right
}
}
}
}
Just use Math.max:
function largest(array) {
return Math.max.apply(Math, array);
}
console.log(largest([5,-2,7,6]));
If you really want to use a custom binary larger function, consider [].reduce:
function larger(num1, num2) {
return num1 > num2 ? num1 : num2;
}
function largest(array) {
return array.reduce(larger, -Infinity);
}
console.log(largest([5,-2,7,6]));
The simpliest solution is tu use a max tmp value. This way, you only need to do one iteration over all your array.
function largest(array){
var max = array[0];
for (var i = 1; i < array.length ; i++) { // So we start at 1
max = larger(max, array[i]);
// Or use this : if(array[i] > max) max = array[i];
}
AS SAID BY ORIOL
I didn't check the length of the array, the above solution work only if the array.length > 0.
Otherwise, you'll have to check it usingsomething like this instead of var max = array[0];
function largest(array){
var max = -Infinity;
for (var i = 0; i < array.length ; i++) { Start at 0
max = larger(max, array[i]);
}
It really depends on the ergonomics of your IHM.
Iterate through the array once, keeping only the largest:
function larger(num1, num2){
var largerNumber = 0;
if (num1 > num2){
largerNumber = num1;
} else {
largerNumber = num2;
}
return largerNumber;
}
function largest(array){
let largestNumber = array[0];
for (var i = 1; i < array.length ; i++){
largestNumber = larger(largestNumber, array[i]);
}
return largestNumber;
}
var test = [1, 53, 352, 22, 351, 333, 123, 5, 25, 96];
console.log(largest(test));
If you are just trying to find the maximal value, you should go with Oriol's answer: Math.max
If you are looking for a way to call one function from another you can do it like this:
function first_function() {
//code of first function
//call to the other function
second_function();
}
function second_function() {
//code of second function
}
Set the first element of array to a variable, if next element in array is greater set variable to that element; continue process, return variable
function largest(array) {
if (!array.length) return;
for (var i = 0, curr = void 0; i < array.length ; i++) {
if (curr === void 0) curr = array[i];
else if (curr < array[i]) curr = array[i];
}
return curr
}
console.log(largest([2,20,2000,2,7]));
This is a program that I have wrote to solve a problem. Check if there exists a sum of elements that equal to the maximum number in the array, return true if so, false otherwise.
var found = "false";
var max;
function ArrayAdditionI(array) {
max = Math.max.apply(null,array);
var p = array.indexOf(max);
array.splice(p,1);
array.sort(function(a, b){return a-b;});
found = findSum(array, 0, 0);
return found;
}
function findSum(array, sum, startIndex){
for(var i = startIndex; i < array.length ; i++){
sum += array[i];
if(sum === max){
found = "true";
break;
}else if(sum > max){
break;
}
if(i+2 < array.length && sum < max){
findSum(array, sum, i+2);
}
}
if(startIndex < array.length && sum !== max){
return findSum(array, 0, startIndex+1);
}
return found;
}
ArrayAdditionI(readline());
I had to use global variable, found, to indicate where a sum has been found or not. The return statement always returned undefined.
Also, if I use a return statement in the following if statement, the code does not work properly.
if(i+2 < array.length && sum < max){
return findSum(array, sum, i+2);
}
This is not the optimal solution to the problem, but this is the version I got working.
My question is Why am I getting undefined if I use return statement within the if statement. Also, I tried not using global and use return true if sum === max and at the very end return false, it always returns false or undefined.
-- UPDATE 2: Code with error results --
function ArrayAdditionI(array) {
var max = Math.max.apply(null,array);
//remove max element from array
var p = array.indexOf(max);
array.splice(p,1);
//sort array
array.sort(function(a, b){return a-b;});
//call find sum function
return findSum(array, 0, 0, max);
}
function findSum(array, sum, startIndex){
for(var i = startIndex; i < array.length ; i++){
sum += array[i];
if(sum === max){
return true;
}else if(sum > max){
break;
}
if(i+2 < array.length && sum < max){
**return** findSum(array, sum, i+2, max);
}
}
if(startIndex < array.length && sum !== max){
return findSum(array, 0, startIndex+1, max);
}
return false;
}
// calling the first function
ArrayAdditionI([ 7, 2,90, 31, 50 ]);
The start of the program is this call: ArrayAdditionI([ 7, 2,90, 31, 50 ]);
The return should be true.
Also, ArrayAdditionI([ 1,2,3,4 ]); is true.
However, ArrayAdditionI([ 1,2,3,100 ]); is false.
The return statement between ** **, when removed the code works, otherwise I either get false or undefined. I do not understand this part! Why does removing the return solves the problem, I thought every recursive call must be proceeded with a return statement.
Is the problem maybe due to multiple calls ? Am I using recursion in the improper way?
There are a few mistakes on your code that could lead to the error.
T.J. Crowder already said, use actual booleans instead of a string.
The found variable isn't defined inside your findSum function. That makes JavaScript assume you're setting a global variable.
Add var found = false; as the very first line of your findSum function.
Inside the last if inside your for there are a call to the findSum function but it's not returning it's value nor assigning it to the found variable.
Fix those and update your question with the results.
The following function should give you a true or false answer as to whether or not any combination of values inside an array produces the max figure.
var a = [
1, 1, 1, 1, 1, 1,
1, 1, 1, 9
]
var b = [1,1,1,5]
function MembersHoldMaxSum(arr) {
var i, r = false, index, max = Math.max.apply(null, arr), index;
for (i = 0; i <= arr.length - 1; i++) {
for (index = 0; index <= arr.length - 1; index++) {
var new_arr = [], ct;
for (ct = 0; ct <= arr.length - 1; ct++) {
if (index != ct) { new_arr.push(arr[ct]) }
}
while (new_arr.length != 1) {
var sum = 0, ct2 = 0;
for (ct2 = 0; ct2 <= new_arr.length - 1; ct2++) {
sum += new_arr[ct2];
}
if (sum == max) { return true }
new_arr.pop()
}
}
}
return r
}
var returns_true = MembersHoldMaxSum(a);
var returns_false = MembersHoldMaxSum(b);
i want to write a JavaScript function which finds the difference between the biggest and the smallest number. Input may be any number, so I use arguments.
I wrote a max and a min function, alone they are working fine. I have put them in a difference function to calculate max-min and return the result.
But there is a bug somewhere, the code is not running as expected.
<!DOCTYPE html>
<html>
<body>
<p>Finding the difference.</p>
<p id="demo"></p>
<script>
function difference() {
var diff = 0;
function findMax() {
var i, max = 0;
for(i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
function findMin() {
var i, min=Infinity;
for(i = 0; i < arguments.length; i++) {
if (arguments[i] < min) {
min = arguments[i];
}
}
return min;
}
diff=max-min;
return diff;
}
document.getElementById("demo").innerHTML = difference(4, 5, 6,88);
</script>
</body>
</html>
Try this instead
function difference() {
var i, val = parseFloat(arguments[0]), min = val, max = val;
for(i = 1; i < arguments.length; i++) {
val = arguments[i];
min = Math.min(val, min);
max = Math.max(val, max);
}
return max - min;
}
no need for infinity either
You never call either findMin() or findMax().
You can use the builtins Math.min() or Math.max() instead, they both take an unlimited number of arguments so you can avoid iterating over the arguments yourself.
Like so:
function difference() {
var min = Math.min.apply(null, arguments),
max = Math.max.apply(null, arguments);
return max - min;
}
If for some reason you wish to make use of your existing findMin() and findMax() methods, you are only missing the invocation of these methods.
Inside difference(), you should do this:
var numbers = Array.slice(arguments); // create an array of args
var max = findMax.apply(this, numbers);
var min = findMin.apply(this, numbers);
return max - min;
And do fix your findMax() method as suggested by a comment if you wish to handle negative numbers.
You can do it in one for loop much easier:
var numbers = [4, 8, 1, 100, 50];
function difference(arr) {
var max = arr[0]
var min = arr[0];
for(var i = 0; i < arr.length; i += 1) {
if(arr[i] > max) {
max = arr[i];
}
if(arr[i] < min) {
min = arr[i];
}
}
var d = max - min;
return d;
}
var result = difference(numbers);
console.log(result);