Sort and print number of occurences of random numbers - arrays

const randomNum = [];
for (let i = 0; i <= 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
then
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
My goal is to print out something along the line of
Number 1, 6, 12, 3, 9 occurred 1 times.
Number 2, 5, 7, 19, 17 occurred 2 times.
Number 15, 11 occurred 3 times.
And so on.
Any idea how i should go about this?
I was thinking of making a function, something along the line of
function numberOccurrence(arr, arrLength){
}
So i in the future could feed it ANY array with with x amount of numbers in it, but I'm unsure how to go forward.
I've tried multiple .includes, .indexOf, ifs and so forth, but i feel stuck, could anyone give me a push in the right direction?
I feel like having a loop which counts how many times 1 occurs, then saves that into an object like this
numObj = {
1: 2,
2: 1,
3: 4,
}
Where the object is built as soon as the function runs, and it builds it based on the arrLength parameter i feed the function in the beginning.
Anything is appreciated, thank you!
Update:
I manage to SOMETIMES print part of the answer right with this:
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
let numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
if (j === randomNum.length) {
printOut(`Number: ${numOccurr.join(', ')} occurrs ${i} times.`);
numOccurr = [];
}
}
}
}
}
if i check my array after "Number: 20 occurred 4 times" gets printed, i see that the answer is correct, problem is, sometimes it prints every number generated 1 time, then sometimes only those generated 2 times, and so on. And sometimes nothing gets printed

SOLVED:
This code worked for me
const randomNum = [];
for (let i = 0; i < 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
const numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
}
}
}
if (numOccurr.length !== 0)
printOut(`Number: ${numOccurr.join(', ')} occurred ${i} times.`);
}

Related

Comparing variable to Math.max(...arr) not returning accurate answer

I'm trying to complete an easy LeetCode question: https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ but cannot figure out why my code is not working correctly. Here is the question and a correct solution:
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Here is my current code:
var kidsWithCandies = function(candies, extraCandies) {
let newArr = [];
const max = Math.max(...candies)
for(i=0; i<candies.length; i++) {
let newVal = candies[i] + extraCandies
if (newVal >= max) {
newArr.push('true')
} else {
newArr.push('false')
}
}
return newArr
};
My code is returning [true,true,true,true,true] instead of [true,true,true,false,true].
I've used console.log() to check the values for 'max' and 'newVal' as the loop runs, and they are all correct, so there must be something wrong with my if statement, but I can't figure out what.
Thank you for your help!
You've answered your own question. Nonetheless, this'd also pass on LeetCode:
const kidsWithCandies = (candies, extraCandies) => {
let maxCandies = 0;
const greatest = [];
for (const candy of candies) {
(candy > maxCandies) && (maxCandies = candy);
}
for (let index = 0; index < candies.length; ++index) {
greatest.push(candies[index] + extraCandies >= maxCandies);
}
return greatest;
};

I'm trying to randomize 5 selections from a list of people

This might be less difficult than I'm making it out to be, but I'm trying to make a Discord.JS bot command, that will take however many arguments I have. For example: !randomize 1,2,3,4,5,6,7,8,9,10
And the bot would respond with something like: "I have chosen: 4,2,7,3,9!" Any help?
Current attempt: Not exactly sure what I'm doing.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}`
`bot.on('message', async msg => {
if(msg.content === "!add") {
//message.member.user.tag
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var user = args[1];
//if(!args[1]) return msg.channel.send("Please specify an argument!");
if(nameList.includes(user)) {
msg.reply("You're already on the list.")
} else {
nameList.push(args[1]);
msg.channel.send(`${args[1]} has been added to the list!\n Current List:` + nameList);
}
}
if(msg.content === "!bonus") {
if(nameList.length === 0) {
msg.reply("Either the list is empty, or I'm not in the mood!");
} else {
shuffleArray(nameList);
var chosenOne = nameList.pop();
nameList = [];
msg.reply(chosenOne + ' has been chosen! Good luck!');
}
}
if(msg.content === "!list") {
if(nameList.length === 0) {
msg.channel.send("Either the list is empty, or I'm not in the mood!");
} else {
msg.channel.send('The current list:' + nameList);
}
});```
Here's some simple steps to select 5 random elements from an array...
Construct an array of possible selections. In this example I've used names for the first 10 letters of the alphabet. In your code, it'll be the command arguments or predefined nameList.
Make a new array to hold the elements picked.
At some point before #3, you should check to make sure the pool the user has provided is large enough to make 5 selections (Array.length).
Use a for loop to execute the next code multiple times.
Generate a random number representing the index of a selected element (Math.random(), Math.floor()/double NOT bitwise operator).
Push the selection into the array.
Remove the chosen element from the original pool (Array.splice()).
Return the results.
const pool = ['Albert', 'Bob', 'Charlie', 'David', 'Edward', 'Francis', 'George', 'Horacio', 'Ivan', 'Jim'];
const selected = [];
for (let i = 0; i < 5; i++) {
const num = ~~(Math.random() * pool.length);
selected.push(pool[num]);
pool.splice(num, 1);
}
console.log(`I have chosen: ${selected.join(', ')}`);
Take this example and manipulate it within your code to suit your purpose.

es6 for loop not looping

I am trying to get a simple ES6 for-loop working but cant figure out why its not running.
I've copied an example from developer.mozilla docs and I've also tried it with the eslinter version which is below:
I have also added a let i = 0; above. All it renders/logs is i = 0 and wont increment.
the eslint version is here: eslint site
for (i = 0; i < 10; i += 1) {
console.log('i', i);
return <p>component {i}</p>;
}
Edit: ok got the values coming back in the log as i=0, i=1, etc... but to get them into a component each? i tried the push into array and mapping through to get the components out but i get no error and nothing appearing, even if i try just getting a value out.
const nbPageArray = [];
let i = 0;
for (i = 0; i < nbPages; i += 1) {
console.log('i', i);
nbPageArray.push(<p>component {i}</p>);
}
console.log('array', nbPageArray);
nbPageArray.map(a => <p>{a.type}</p>);
}
final working version:
const nbPageArray = [];
for (let i = 0; i < nbPages; i += 1) {
nbPageArray.push({ page: i + 1 });
}
return nbPageArray.map(a =>
<li className="page-item"><a className="page-link">{a.page}</a></li>,
);
Main issue is i += 10;
That should be 1 += 1;
And You should return array of elements :
var p_tags = [];
for (i = 0; i < 10; i += 1) {
console.log('i', i);
p_tags.push(<p>component {i}</p>);
}
return p_tags;
Edited question's answer :
First Error:
const nbPageArray = []; should be var nbPageArray = [];
Second You are not returning the array so change your code to this
return nbPageArray.map(a => <p>{a.type}</p>);
If you return from your for loop, you will exit the current function, you are also incrementing i by 10 each trip so you will exit the loop after one round either way.
If you are trying to print a string with the value of i ten times you could try using template string like so:
for (i = 0; i < 10; i += 1) {
console.log('i', i);
console.log(`<p>component ${i}</p>`);
}
you are returning from the loop and also incrementing by 10. The loop will execute only once.
As said in the comments, the return inside the for loop is going to exit from the function at the first iteration.
You can do something like this instead:
const result = Array(10).fill().map((_, i) =>
<p>component {i}</p>
);
Or
const result = [...Array(10)].map((_, i) =>
<p>component {i}</p>
);

Loop won't break in javascript

So I am trying to create a function where it will display to me the FIRST even number divisible by 2. The values to be divided are inside an array and another function helps me determine whether the values in the array are divisible by 2. The problem is that the loop won't break and the loop continues until the last value of the array. I want it to break once it finds the first number divisible by 2. So in this case the loop should stop once it reaches value 8 in the array but it doesn't and continues until 10. I hope you can help me
This is my code:
function findElement(arr, func) {
var num = 0;
arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; });
I believe your for over array is off.
Instead of
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
It should be
for(var i = 0; i <= arr.length-1; i++) {
Otherwise, you might as well be verifying undefined array indexes.
Please remove arr.sort() your function works find
please find the updated code .its working fine run and check.
function findElement(arr, func) {
var num = 0;
// arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
console.log(findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; }));

Multidimensional Arrays and one of the fields

There is a multi-d array and I want to reach specific field in it. I have look around it but I was unable to find proper answer to my question.
My array is like that;
array-md
columns-- 0 | 1 | 2
index 0 - [1][John][Doe]
index 1 - [2][Sue][Allen]
index 2 - [3][Luiz][Guzman]
.
.
.
index n - [n+1][George][Smith]
My question is how can I reach only second column of the array? I tried name = array[loop][1]; but it says "Cannot access a property or method of a null object reference". What is the right way to do that?
Here is main part of the code.
get
var lpx:int;
var lpxi:int;
var arrLen:int = Info.endPageArray.length;
for(lpx = 0; lpx < arrLen; lpx++)
{
for(lpxi = Info.endPageArray[lpx][2]; lpxi < Info.endPageArray[lpx][1]; lpxi++)
{
if(Info._intervalSearch[lpxi] == "completed")
{
successCount++;
Info._unitIntervalSuccess.push([lpx, successCount / (Info._intervalSearch.length / 100)]);
}
}
}
set
for(lpix = 0; lpix < arrayLength; lpix++)
{
if(lpix + 1 <= arrayLength)
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix + 1], Info._UnitsTriggers[lpix]]);
}
else
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix], Info._UnitsTriggers[lpix - 1]]);
}
}
Try this:
var tempArr:Array = [];
function pushItem(itemName:String, itemSurname:String):void
{
var tempIndex:int = tempArr.length;
tempArr[tempIndex] = {};
tempArr[tempIndex][tempIndex + 1] = {};
tempArr[tempIndex][tempIndex + 1][name] = {};
tempArr[tempIndex][tempIndex + 1][name][itemSurname] = {};
}
function getNameObject(index:int):Object
{
var result:Object;
if(index < tempArr.length)
{
result = tempArr[index][index + 1];
}
return result;
}
pushItem("Max", "Payne");
pushItem("Lara", "Croft");
pushItem("Dart", "Vader");
//
trace(getNameObject(0));
trace(getNameObject(1));
trace(getNameObject(2));
Multidimensional array is an array of arrays, which you can create like this :
var persons:Array = [
['John', 'Doe'],
['Sue', 'Allen'],
['Luiz','Guzman']
];
var list:Array = [];
for(var i:int = 0; i < persons.length; i++)
{
list.push([i + 1, persons[i][0], persons[i][1]]);
}
trace(list);
// gives :
//
// 1, John, Doe
// 2, Sue, Allen
// 3, Luiz, Guzman
Then to get some data :
for(var j:int = 0; j < list.length; j++)
{
trace(list[j][1]); // gives for the 2nd line : Sue
}
For more about multidimensional arrays take a look here.
Hope that can help.

Resources