I have a school project I am workin gon and I am really struggling to figure this one out..
The project is to generate a list of 1000 random numbers between 1 and 10 and then removing every instance of 7 in this list. But the tricky part is that we are supposed to count the amount of removed 7s and printing this to the console...
Any ideas?
This is not my code and is just something I am playing around with but this is what I got so far.
<!-- Document Required Information -->
<!doctype html>
<!-- Language & Input Types -->
<html lang="no">
<meta charset="utf-8">
<!-- utf-8 gjør at vi kan bruke æ, ø og å -->
<head>
<title> Oppgave 3 Prøve 3D - 3F - Julian </title>
</head>
<body>
<script>
function getRandomExcept(min, max, except) {
except.sort(function(a, b) {
return a - b;
});
var random = Math.floor(Math.random() * (max - min + 1 - except.length)) + min;
var i;
for (i = 0; i < except.length; i++) {
if (except[i] > random) {
break;
}
random++;
}
return random;
}
(function(min, max, except) {
var iterations = 1000;
var i;
var random;
var results = {};
for (i = 0; i < iterations; i++) {
random = getRandomExcept(min, max, except);
results[random] = (results[random] || 0) + 1;
}
for (random in results) {
console.log("Antall 7 Fjernet " + except.length + " Tall: " + random + ", Antall: " + results[random] + ", sjanse: " + results[random] * 100 / iterations + "%");
}
})(1, 10, [7]);
</script>
</body>
</html>
This is a simple solution:
// Start with an empty array
let numbers = [];
// Do a for loop where you generate your 1000 numbers
for(let i = 0; i < 1000; ++i) {
// Math.random() return a floating number from 0 to 1 (exclusive), if you multiply it by 10
// you get a floating number between 0 and 10 (exclusive). Math.floor() cuts the decimal part
// giving you an integer number between 0 and 9, so you add 1 to get a number between 1 and 10
numbers.push(Math.floor(Math.random() * 10) + 1);
}
// You can use filter to remove the sevens
numbers = numbers.filter(el => el !== 7);
// Then you can just compare the length of the array
const removed = 1000 - numbers.length;
console.log(removed);