user10142451
user10142451

Reputation:

Find the maximum number or largest value from given array

My project module contains a lot of practice questions, from that one question I picked and tried to solve, below is the question.

Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. Input: The first line contains an integer N, Next line contains N integers separated by space. Output: Print the maximum number that can be obtained by using given numbers. Constraints: 1<=N<=1000 1<=Number<=1000000

HTML:

Enter Number:   <input type="text" id="userinput"  class="clr"/>    <br> 
<br>
Largest Value:    <input type="text" id="out"  class="clr"/> <br> <br>

Javascript:

function myFun() {
 let b = document.getElementById("userinput").value;
 let c = b.split(" ");                    
 var maxCombine = (a) => +(a((x, y) => +("" + y + x) - +("" + x + y)).join(''));

document.getElementById("out").value = ([
 c
 ].map(a));
 };

I'm getting an error while running the script for wrong declaration variable. Please give a suggestion.

Error:

Uncaught ReferenceError: a is not defined
at myFun (lagnum.html:26)
at HTMLButtonElement.onclick

Upvotes: 0

Views: 266

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

Just another approach by using sort with String#localeCompare.

There is no need to conver splitted items to string, because after using String#split, you get an array of strings.

var string = '54 546 548 60 80 8';

console.log(
    string
        .split(' ')
        .sort((a, b) => (b + a).localeCompare(a + b)).join(' ')
);

Upvotes: 0

Nezir
Nezir

Reputation: 6925

With small changes here is working sample:

function myFun() {
  let b = document.getElementById("userinput").value;
  let c = b.split(",");
  var maxCombine = (a) => +(a.sort((x, y) => +("" + y + x) - +("" + x + y)).join(''));

  document.getElementById("out").value = ([
  c
  ].map(maxCombine));
  };
Enter Number:   <input type="text" onfocusout="myFun()"; id="userinput"  class="clr"/>    <br> 
<br>
Largest Value:    <input type="text" id="out"  class="clr"/> <br> <br>

Upvotes: 0

user10203040
user10203040

Reputation:

In your code you have missed 2 things, check below points.

i) After split the value you're combining but there you forgot to sort the values to find largest ii) While mapping the output you have called wrong variable

Please check the below code,

function myFun() {
  let b = document.getElementById("userinput").value;
  let c = b.split(" ");
  var maxCombine = (a) => +(a.sort((x, y) => +("" + y + x) - +("" + x + y)).join(''));

  document.getElementById("out").value = ([
  c
  ].map(maxCombine));
  };

Upvotes: 5

Related Questions