Jump to content

Adivinhar número de caracteres


Sofia Borges

Recommended Posts

Hello Malta. 
Cá estou novamente a precisar de ajuda. Já estou a deitar fumo pela cabeça! 

Tenho este enunciado:

<Hacking Task #2>

Congratulations, you now know the *very* basics of the JavaScript language!
To proceed on your mad journey from programming n00b to full-fledged <Code Cadet>, you must now work alongside fSociety's ultra dope hacking crew and show them your awesome recently acquired skills in a series of <Hacking Tasks>.
For this task you'll need to gain access to a target's account, which is password protected. We know the password is only four characters long, but we have no idea of what it looks like.
With today's computing power, brute-forcing weak passwords is not that hard and, as in any brute-force technique, it only requires time and luck.

Instructions
You know that your target's password is 4 characters long, so you'll just have to brute force 1 character at a time. We already declared the variable correctGuesses which you should use to keep track of how many characters you have guessed so far.
Bear in mind that your program does not need to guess the password, that is not your goal!
You need to create a loop that only stops when all 4 characters have been guessed. On each loop iteration you need to calculate a random number between 1 and 3, which will correspond to each of the bellow scenarios:
1. You guessed one character correctly, which increases correctGuesses by 1 and prints the message 'Found X characters' (where X is replaced with the current number of correct guesses).
2. You guessed incorrectly and your target's terminal has detected too many attempts, which resets correctGuesses to 0 and prints the message 'Starting over' to the console.
3. You guessed incorrectly, but have not been detected yet, correctGuesses is kept with the same value.
Once the password is cracked (that is, correctGuesses has a value of 4) you should print the message 'Terminal hacked!'.

Make sure all the messages in your code are in the correct format in order to advance!

 

Já fiz e refiz o código várias vezes, tenho assim:

var correctGuesses = 0;
var targetPassword = 4;
while(correctGuesses < 4) {
    var outcome = Math.floor(Math.random()*3);
  	if(outcome === 0){
    	correctGuesses ++;
    	console.log ('Found ' + correctGuesses + ' characters');
  }
 	if (outcome === 1) {
    	correctGuesses = 0;
    	console.log ('Starting over');
  }
  	if (outcome === 2) {
    	console.log ('Wrong guess');
  }
    if (correctGuesses === targetPassword) {
    	console.log('Terminal hacked!');
        break;
    }
}

mas dá-me erro: >>>>Code is incorrect Not sure how you can calculate a random number between 1 and 3 in such a way

Será que conseguem dizer-me o que tenho de melhorar? 

Obrigada desde já

Link to comment
Share on other sites

Em 30/09/2020 às 12:31, Sofia Borges disse:

Claro! 🤦‍♀️

Obrigada Já corrigi:  



var outcome = Math.ceil(Math.random()*3);

Agora o erro é: >>>>Code is incorrect You guessed some characters correctly, but failed to do the right thing!

Ajustou os IF's (=0, =1, =2) para (=1, =2, =3)?

Senão o "0" nunca ocorre e ficará num ciclo infinito (correctGuesses=0)

cps,

Link to comment
Share on other sites

1 minuto atrás, Zex disse:

Math.floor(Math.random()*3) 

dá 0, 1 ou 2

então 1+Math.floor(Math.random()*3) 

dá 1, 2 ou 3

ou Math.floor(1+Math.random()*3) 

dá 1, 2 ou 3

Obrigada. 

Se colocar: var outcome = Math.ceil(Math.random()*3); 
o erro é: >>>>Code is incorrect You guessed some characters correctly, but failed to do the right thing!

Se colocar: Math.floor(Math.random()*3)  ou Math.floor(1+Math.random()*3) 
o erro é: >>>>Code is incorrect Not sure how you can calculate a random number between 1 and 3 in such a way

Se colocar: 1+Math.floor(Math.random()*3) 
o erro é: >>>>Code is incorrect You guessed some characters correctly, but failed to do the right thing!

Link to comment
Share on other sites

5 minutos atrás, Zex disse:

O código

if (correctGuesses === targetPassword) { console.log('Terminal hacked!'); break;

deve ficar depois do ciclo while

Nesse caso bastará escrever 

console.log('Terminal hacked!');

Bem pensado. Mas não é isso. Ao colocar esse console.log depois do ciclo while o erro mantém-se igual. 

 

(já estou a bater mal.. isso é para entrar num bootcamp... isto deveria ser básico que é para quem nunca programou...)

Link to comment
Share on other sites

Em 01/10/2020 às 17:05, susete disse:

Olá Sofia, Já encontraste-te a resposta?

 

Olha bem para o ponto 3, "3. You guessed incorrectly, but have not been detected yet, correctGuesses is kept with the same value."

O erro está nesse if 🙂

Ola Lisete! Obrigada! 

Ja resolvi. Ontem, já tarde, descansei a cabeça meia hora e pensei l: "é agora ou nunca". Olhei para a enunciado com cautela e consegui resolver. 

 

Agora estou noutro que parece, igualmente, simples mas encalhei!!😜

Link to comment
Share on other sites

Olá, boa noite ^^

Recentemente tenho focado mais na área de programação apenas como hobbie e este exercício apareceu-me no feed e devido à "noobice", não consigo entender o que está errado no código que publicou 🤔 genuinamente, parece-me correcto (do pouco que sei).

 

Obrigada.  

Link to comment
Share on other sites

4 horas atrás, Zex disse:

 

O código funciona.

O problema principal é que era um computador a corrigir e os computadores são pouco flexíveis.

var passwordLength = 4;
var correctGuesses = 0;

while (correctGuesses < 4) {
	var outcome = Math.ceil (Math.random () * 3);
	
	if (outcome === 1){
		correctGuesses ++;
	console.log ('Found ' + correctGuesses + ' characters');
        
	}
	else if (outcome === 2){
		correctGuesses = 0;
		console.log ('Starting over');
	}
	else if (outcome === 3){
       correctGuesses = correctGuesses; 
	}
}

if (correctGuesses === passwordLength) {  
	console.log ("Terminal hacked!");

}

Esta era a forma que eles queriam. 😉

Edited by Sofia Borges
resolvido
Link to comment
Share on other sites

7 horas atrás, Zex disse:

 

O código funciona.

O problema principal é que era um computador a corrigir e os computadores são pouco flexíveis.

Ah okay, então ambas as maneiras estão correctas (e provavelmente existe mais modos de fazer o exercício) caso o código fosse corrido/lido por uma pessoa. 

Obrigada :)

Link to comment
Share on other sites

3 horas atrás, Sofia Borges disse:

var passwordLength = 4;
var correctGuesses = 0;

while (correctGuesses < 4) {
	var outcome = Math.ceil (Math.random () * 3);
	
	if (outcome === 1){
		correctGuesses ++;
	console.log ('Found ' + correctGuesses + ' characters');
        
	}
	else if (outcome === 2){
		correctGuesses = 0;
		console.log ('Starting over');
	}
	else if (outcome === 3){
       correctGuesses = correctGuesses; 
	}
}

if (correctGuesses === passwordLength) {  
	console.log ("Terminal hacked!");

}

Esta era a forma que eles queriam. 😉

Esclarecida, admito que ainda não passei muitas horas em JS e graças a este exercício fiquei a perceber que se pode ter "if statements" e "else-if statements" no mesmo block! 

 

Obrigada pela disponibilidade :) 

Link to comment
Share on other sites

  • 2 months later...
  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.