0

I have completed a JavaScript course and now I am stuck with first Hands-on problem. The question is "How to generate Random Character id"

Review below screen:

HTML code

enter image description here

JavaScript Code.

enter image description here

Error message

enter image description here

Please let me know your suggestions

Thanks

The code I used after few suggestions is as below:

function stringGen(yourNumber){
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < yourNumber; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

 return text;
}

stringGen(10);

I get the below error when I test the code in Node.js in Hackerrank

09 10 2018 06:15:13.648:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/                                                      
09 10 2018 06:15:13.651:INFO [launcher]: Launching browser jsdom with unlimited concurrency                                                    
09 10 2018 06:15:13.656:INFO [launcher]: Starting browser jsdom                                                                                
09 10 2018 06:15:13.828:INFO [Node.js (linux; U; rv:v8.9.4)]: Connected on socket 1L0-mKrQnWEv092UAAAA with id 34735969                        
Node.js (linux; U; rv:v8.9.4) Random string checking random number FAILED                                                                      
        Expected 0 to be 4.                                                                                                                    
            at UserContext.<anonymous> (test/index_test.js:17:33)                                                                              
Node.js (linux; U; rv:v8.9.4) Random string comparing random numbers FAILED                                                                    
        Expected true to be false.                                                                                                             
            at UserContext.<anonymous> (test/index_test.js:26:16)                                                                              
Node.js (linux; U; rv:v8.9.4): Executed 2 of 2 (2 FAILED) ERROR (0.031 secs / 0.016 secs)                                                      
npm ERR! Test failed.  See above for more details.  
Mahesh Garade
  • 11
  • 1
  • 1
  • 2
  • 5
    If you could, please edit *your actual code* as text into your question - images of code *alone* are [tedious and difficult](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) to work with and debug. It forces those who would otherwise love to help you to [transcribe your image](https://idownvotedbecau.se/imageofcode) first, which is a waste of time. – CertainPerformance Oct 09 '18 at 05:01
  • https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript – Kevin Welch Oct 09 '18 at 05:08
  • Can you share your code? – Narendra Oct 09 '18 at 05:11
  • function stringGen(i){ var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } console.log(stringGen(8)); – Mahesh Garade Oct 09 '18 at 05:23
  • @Kevin Welch Its not really about generating the id. That part works perfect in console or Atom. The part I need help with is with the interface where I am placing my code and submit it throws an error. – Mahesh Garade Oct 09 '18 at 05:24
  • Error Node.js (linux; U; rv:v8.9.4) Random string checking random number FAILED Expected 5 to be 4. at UserContext. (test/index_test.js:17:33) Node.js (linux; U; rv:v8.9.4): Executed 2 of 2 (1 FAILED) (0.023 secs / 0.014 secs) npm ERR! Test failed. – Mahesh Garade Oct 09 '18 at 05:27
  • Don't past relevant information like code in the comment section. use the [edit](https://stackoverflow.com/review/suggested-edits/21077080) link and add the code to your question. – t.niese Oct 09 '18 at 05:43
  • @MaheshGarade You are still returning text from function. try to document.getElementById("result").innerHTML= text; – Narendra Oct 09 '18 at 06:24

7 Answers7

2
function stringGen(){
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var x = document.getElementById("num").value;
  for (var i = 0; i < x; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}
cvpathi
  • 21
  • 5
0
function stringGen(yourNumber){
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < yourNumber; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

call Function stringGen(8)

it will generate random string

  • Thank you for your prompt response. Let me try it. – Mahesh Garade Oct 09 '18 at 05:10
  • Does not work. I get the below error: Node.js (linux; U; rv:v8.9.4) ERROR Unexpected number at vm.js:80 – Mahesh Garade Oct 09 '18 at 05:18
  • Don't put document.getElementById in your stringGen function, it will throw an error when you unittest in Node. Instead send the stringLength number as an argument. This is generally advised in order to keep a "separation of concerns". – Kevin Welch Oct 09 '18 at 05:31
0

This worked for me.

function stringGen()
{
   //Type your code here.
   var length = document.getElementById('num').value;
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   document.getElementById("result").innerHTML= result;
   return result;
}
rajkumar21
  • 183
  • 3
  • 9
-1

Alright, so I updated my answer. I hope this works for you. Happy coding and welcome to SO :)

const makeid = () => {
  let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let id = "";
  let num = document.getElementById('input_id').value;

  for (let i = 0; i < num; i++) {
    id += chars.charAt(Math.floor(Math.random() * chars.length));
    document.getElementById('info1').innerHTML = id;
    document.getElementById('info2').innerHTML = id.length;
    }
  }
#info1 {
  color: green; 
  font-weight: bold;
  letter-spacing: 1px;
}

#info2 {
  color: red;
  font-weight: bold;
}
    <input type="number" id="input_id" value="">
    <input type="button" value="Submit" onclick="makeid()" />
        
    <div>Your unique id is: 
        <span id="info1"></span>
    </div>
    <div>The length of your id is: 
        <span id="info2"></span>
    </div>
Dženis H.
  • 7,284
  • 3
  • 25
  • 44
  • Thank you. However, I am trying to submit my answer on the hackerrank portal as it is using NodeJS i guess and it throws an error – Mahesh Garade Oct 09 '18 at 05:49
  • @ Mahesh - Okay, so what am I supposed to do with that 'info' now ?! If you understand the error, you (almost) have the answer. Meaning the solution can be found in the problem itself. But if you don't know what the error is or at least suggesting the cause of the issue, then you're lost. HackerRank is for practice. So, practice buddy and good luck :) Google is your friend when it comes to gathering knowledge and problem (error) solving, but not to copy/ paste solutions that people posted earlier. @Narendra Two guys posting the exact same code and arguing about which one is better. SMH! – Dženis H. Oct 09 '18 at 06:20
  • Why are you exchanging words on my post? Are you being serious? I'm getting notifications that have nothing to do with me. **:)** – Dženis H. Oct 09 '18 at 06:22
  • 2
    Apologies. I am new to JavaScript and this is my first post on Stack Overflow. – Mahesh Garade Oct 09 '18 at 06:26
  • No worries, I'm sorry dude. Keep learning. `JS` is great once you get the hang of it ;) All I'm saying is hard to "help" you if there isn't enough info provided. Cheers! – Dženis H. Oct 09 '18 at 06:38
  • That was really great. Thank you very much. As advised I am going through the tutorial you suggested. However, please help me with your email if you want to me to share my screen via teamview and show you that the Hackerrank is really expecting something else. It is again throwing an error. – Mahesh Garade Oct 09 '18 at 08:57
  • TypeError: Cannot read property 'value' of null Note: I replaced your function name with stringGen – Mahesh Garade Oct 09 '18 at 09:03
  • Have you entered a value? Did you run the code snippet above? There's a big blue button that says: **"Run code snippet"** with a play icon in it. Enter a number inside and see what happens. The `ids` and `class` names have to match also. Have a nice day. – Dženis H. Oct 09 '18 at 10:02
-1
function stringGen(yourNumber){
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < yourNumber; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

 document.getElementById("result").innerHTML= text;
}
Narendra
  • 4,514
  • 2
  • 21
  • 38
-1

Answer

    function stringGen()
{
    var num = document.getElementById('num').value;
   //  alert(num);
         var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < num; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

 //alert(text);
 document.getElementById('result').innerHTML = text;
  return text;
}
Ved Prakash
  • 487
  • 5
  • 9
-1
{   
    var c = document.getElementById("num").value;
    let random_string = '';
    let random_ascii;
    let low = 65;
    let high = 90
    for(let i = 0; i < c; i++) {
        random_ascii = Math.floor((Math.random() * (high - low)) + low);
        random_string += String.fromCharCode(random_ascii)
    }
    return random_string
}
kgangadhar
  • 4,886
  • 5
  • 36
  • 54
  • 2
    Maybe you can add a bit explaining how this code snippet helps resolve the problem? Thanks – Thomas Sep 21 '20 at 12:37