Repeated Number count result in Ascending order - javascript

i was trying to get counted result in Ascending order
The following is my code
var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
var SortNewArray = NewArray.sort();
var SortNewArrayLength = SortNewArray.length;
var prev = SortNewArray[0];
var count = 1;
for(var i =0; i<SortNewArrayLength; i++)
{
if(SortNewArray[i] == prev)
{
count++;
}
else
{
console.log(SortNewArray[i] + " comes " + count + " times ");
prev = SortNewArray[i];
count = 1;
}
}
this is output i am getting
whatever i marked in red color. i want those count in ascending order
Please anyone can help me out?

var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
var counts = {};
// first collect the count of each number
NewArray.forEach( function(n){
if( counts[n] ){
counts[n] += 1;
}
else {
counts[n] = 1;
}
});
// now counts = { 1:3, 2:3, 3:1, 4:4, 5:2, 6:1, 7:1 }
// get the keys (unique numbers from NewArray) and sort them by their values (count)
var keys = Object.keys( counts ).sort( function(a, b){
return counts[a] > counts[b];
})
// print key:value pairs sorted by value
keys.forEach( function( n ){
console.log("%s comes %d times", n, counts[n] );
})
/*
3 comes 1 times
6 comes 1 times
7 comes 1 times
5 comes 2 times
1 comes 3 times
2 comes 3 times
4 comes 4 times
*/
http://jsfiddle.net/s384qq66/

Change var count = 1; to var count = 0; and change
console.log(SortNewArray[i] + " comes " + count + " times ");
to
console.log(SortNewArray[i-1] + " comes " + count + " times ");

Related

Missing element in the function

This function should create and display an array with numbers. There is some element missing which prevents this array from displaying and so fulfilling the "console.log" assumptions:
function createArray(number) {
var newArray = [/*10*/];
for(var counter = 1; counter <= number; counter++) {
newArray.push(counter);
}
}
console.log("table with numbers up to 6 = " + createArray(6));
console.log("table with numbers up to 1 = " + createArray(1));
console.log("Testing negatives (should display an empty array) " + createArray(-6));
console.log("Testing 0 (should display an empty array) " + createArray(0));
Could you analyze this and provide some feedback, please?
You're missing return newArray; at the end of the function. If there's no return statement, the function returns undefined by default.
function createArray(number) {
var newArray = [/*10*/];
for(var counter = 1; counter <= number; counter++) {
newArray.push(counter);
}
return newArray;
}
console.log("table with numbers up to 6 = " + createArray(6));
console.log("table with numbers up to 1 = " + createArray(1));
console.log("Testing negatives (should display an empty array) " + createArray(-6));
console.log("Testing 0 (should display an empty array) " + createArray(0));
Well, there is nothing wrong with your function, just you are not returning the array created, just add:
return newArray at the end of the function, linke this:
function createArray(number) {
var newArray = [/*10*/];
for(var counter = 1; counter <= number; counter++) {
newArray.push(counter);
}
return newArray;
}

Click button to get the sum of the first 12 Fibonacci numbers

I want to get and add the first 12 even fibonacci numbers and have it appear on my page when I click the button. Right now my code gets and adds the even numbers. How do I limit it to the first 12 even numbers?
Thank you in advance. http://jsfiddle.net/lakenney/oryygn4y/
// first we get the HTML for the button
var getFibSum = document.getElementById("sumFib");
//then we set the event handler for when the button is clicked
getFibSum.onclick = function(){
document.getElementById("sumFibResult").innerHTML = twelveEvenFibonacciSum();
}
/*
* twelveEvenFibonacciSum - calulates the sum of the first 12 even fibonacci numbers, with 0, 1 being the first two numbers of the sequence
*/
function twelveEvenFibonacciSum(){
/// WRITE YOUR CODE HERE
// Loop that generates Fibonacci numbers.
console.clear();
var fib = [0, 1]; //Initialize array
var sum = 0;
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
}
// Loop until we have 12 even numbers
}
//console.log(fib);
return sumFibResult;
}
Add a variable to the outer scope which gets incremented each time your function is called. Return when this equals 12.
for (var i= 2; i <= 50; i++) {
fib[i] = fib[i-1] + fib[i-2];
var integer = fib[i];
if(integer % 2 == 0) {
// console.log("my current even fib is " + fib[i]);
var sumFibResult = sum += fib[i];
console.log("my current even fib added to sum " + sumFibResult);
timesIncremented++;
}
// Loop until we have 12 even numbers
if(timesIncremented >= 12) {
return;
}
}

Match a range of rows in an array? jQuery, Javascript

I'm unsure how else to write the title but it's about as close as I can get to what I'm after.
I have a calculator I'm trying to create that compares values in a number of arrays.
Each data object in my array has 34 rows, some of which have the same number/value in them.
At the minute if you select france, I only want 1 of each grade to show in the dropdown, so the number 1 would appear once.
If you select France and grade 1, I want the outputted value to say the lowest value in that range to the highest, in this case USA would output 3 to 5 does this make sense?
If so I'm wondering how I'd possibly do this?
JSFiddle
http://jsfiddle.net/R85Qj/
Does this help?
http://jsfiddle.net/R85Qj/2/
$("#convert").on("click", function () {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
/* gradeConversion += "<span>" + countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "</span>";*/
var indexes = [];
var countryIndex = $("#country").val();
var gradeValue = countryGrades[countryIndex].grades[gradeIndex][0];
// find all indexes of gradeValue
for(var i = 0; i < countryGrades[countryIndex].grades.length; i++) {
if (countryGrades[countryIndex].grades[i][1] == gradeValue) {
indexes.push(i);
}
}
allValues = [];
for(var c = 0; c < countryGrades.length; c++) {
gradeConversion += countryGrades[c].country + ":";
for(i = 0; i < indexes.length; i++) {
if (i == 0 || countryGrades[c].grades[indexes[i]][1] != countryGrades[c].grades[indexes[i-1]][1]) {
gradeConversion += countryGrades[c].grades[indexes[i]][1] + " ";
}
}
}
$("#conversions").html(gradeConversion);
});

Javascript: randomly pair items from array without repeats

I am trying to make a very basic "secret santa" generator as one of my first Javascript projects. I have searched for hours for a solution to this problem but so far nothing has worked that I have found.
I have an array of names which need paired to each other. I successfully have them pairing to each other, but right now someone can be drawn twice. I am pushing the randomly chosen names to another array but I can't find a way to check the randomly chosen names against the ones already chosen.
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
var used = [];
var picks = [];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
}
for( var i = 0; i < names.length; i++){
var random = Math.floor(Math.random()*names.length)
if(names[random] == names[i]) {
names[random] = names[random++];
picks.push(names[i] + " gets " + names[random]);
used.push(names[random]);
} else {
picks.push(names[i] + " gets " + names[random]);
used.push(names[random]);
}
}
console.log("picked array: ")
for(var k=0; k<picks.length; k++) {
console.log(picks[k]);
}
console.log("used array: " + used);
Thank you in advance for any help.
Create two arrays with the names, shuffle them, and make sure you don't pick the same name from both arrays :
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
} else {
var arr1 = names.slice(), // copy array
arr2 = names.slice(); // copy array again
arr1.sort(function() { return 0.5 - Math.random();}); // shuffle arrays
arr2.sort(function() { return 0.5 - Math.random();});
while (arr1.length) {
var name1 = arr1.pop(), // get the last value of arr1
name2 = arr2[0] == name1 ? arr2.pop() : arr2.shift();
// ^^ if the first value is the same as name1,
// get the last value, otherwise get the first
console.log(name1 + ' gets ' + name2);
}
}
FIDDLE
I would suggest a different approach. Shuffle, split, and zip, no mutation:
var splitAt = function(i, xs) {
var a = xs.slice(0, i);
var b = xs.slice(i, xs.length);
return [a, b];
};
var shuffle = function(xs) {
return xs.slice(0).sort(function() {
return .5 - Math.random();
});
};
var zip = function(xs) {
return xs[0].map(function(_,i) {
return xs.map(function(x) {
return x[i];
});
});
}
// Obviously assumes even array
var result = zip(splitAt(names.length/2, shuffle(names)));
//^
// [
// [ 'Nick', 'Kimmy' ],
// [ 'Sean', 'Johnny' ],
// [ 'Kyle', 'Brian' ],
// [ 'Cotter', 'Pat' ],
// [ 'Emily', 'Jeremy' ]
// ]
There is a multitude of ways you can achieve this.
The fastest to code, but not necessarily the randomest is:
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
function getPicks(names) {
return names.slice(0).sort(function(){ return Math.random()-0.5 }).map(function(name, index, arr){
return name + " gets " + arr[(index+1)%arr.length];
});
}
getPicks(names);
This is not very random because the shuffling isn't very good and also because you get a single cycle each time. There can be no two cycles A->B->C->A D->E->D.
If you want it to have a random number of cycles of variable length, you can split the names array in several arrays and do the above for each of them, then concatenate the results (see elclanrs).
Finally, the last solution is for each person to pick a person at random and if it's the same one, simply pick again. If the last name remaining in both arrays is the same, simply swap it with another pair.
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
var a = names.slice(0);
var b = names.slice(0);
var result = [];
while (a.length > 1) {
var i = extractRandomElement(a);
var j = extractRandomElement(b);
while (i===j) {
b.push(j);
j = extractRandomElement(b);
}
result.push({ a:i, b:j });
}
if (a[0] === b[0]) {
result.push({ a:a[0], b:result[0].b });
result[0].b = a[0];
} else {
result.push({ a:a[0], b:b[0] });
}
var pairs = result.map(function(item){ return item.a + ' gets ' + item.b});
function extractRandomElement(array) {
return array.splice(Math.floor(Math.random()*array.length),1)[0];
}
I'm a tad late, but thought I'd throw my answer in here. It essentially does the same thing #adeneo's does, but it uses the same basic code as OP:
var names = ["Sean","Kyle","Emily","Nick","Cotter","Brian","Jeremy","Kimmy","Pat","Johnny"];
pickpool = names.slice(0); // Slice the array at the first element to copy it by value
var used = [];
var picks = [];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
}
for( var i = 0; i < names.length; i++){
var random = Math.floor(Math.random()*pickpool.length)
if(names[random] == names[i]) {
// names[random] = names[random++];
picks.push(names[i] + " gets " + pickpool[random++]);
pickpool.splice(random++,1);
} else {
picks.push(names[i] + " gets " + pickpool[random]);
pickpool.splice(random,1);
}
}
console.log("picked array: ");
for(var k=0; k<picks.length; k++) {
console.log(picks[k]);
}
http://jsfiddle.net/SNJpC/
If you don't need to keep the original array you can remove the names as they get selected and each time you pick a name check that it isn't an empty string before pushing it to the next array.
Another consideration...
If you are trying to make a 'Secret Santa' generator, by using random method you can get the same pair next year, and next...
This is another solution where you get all the possible pairs (without repeating a name itself or a pair) for multiple years.
var names = ["Sean", "Kyle", "Emily", "Nick", "Cotter", "Brian", "Jeremy", "Kimmy", "Pat", "Johnny"];
if (names.length % 2 != 0) {
alert("You must have an even number of names. You currently have " + names.length + " names.");
} else {
const arr1 = names.slice()
let arr2 = names.slice();
let countDown = number => {
if (number === 1) {
return;
}
const last = arr2.pop([number - 1]);
arr2.unshift(last);
let pairs = [];
arr1.map(item => {
const index = arr1.indexOf(item);
pairs.push(`${arr1[index]} gets ${arr2[index]}`)
})
console.log(pairs)
return countDown(number - 1);
}
countDown(names.length)
}

Take a string and return number of words in string - JavaScript

I am working on a problem from CoderByte. I am curious about my code. The first function returns 6 and the second function returns 4 which is the correct count. I am trying to understand why that is happening. As when I console log newArr it shows only 4 items.
Here is the problem from CoderByte: - Using the JavaScript language, have the function WordCount(str) take the str string parameter being passed and return the number of words
the string contains (ie. "Never eat shredded wheat" would return 4). Words will be separated by single spaces.
var wordCount = function (str) {
var newArr = str.split(' ');
var total = 0;
for (var i = 0; i < newArr.length; i += 1) {
total += i;
}
return total;
};
///
wordCount('Never eat shredded wheat');
var wordCount = function (str) {
return str.split(' ').length;
};
Because you are adding i instead of one.
total += i;
Basically you have
iteration 1 : total = total + 0 = 0 + 0 = 0
iteration 2 : total = total + 1 = 0 + 1 = 1
iteration 3 : total = total + 2 = 1 + 2 = 3
iteration 4 : total = total + 3 = 3 + 3 = 6

Categories

Resources