-1

I am making a random letters generator. It has to find a given word in the least amount of tries. It lists the number of tries everytime in an array. I want to get the least frequent value in the array.

I already got the most frequent value to work with this

I tried this for lowest frequency but it doesn't work and gives me the last item, with 1 occurence everytime :

var mif = 1;
var itemin;
if (m <= mif) {
    mif = m;
    itemin = generations[i];
}
Joshua
  • 40,822
  • 8
  • 72
  • 132
ttb
  • 75
  • 2
  • 7
  • What does this code do? – Oliver Charlesworth Jun 21 '17 at 08:26
  • creates a minimal frequency variable, and a variable to store the item that has the lowest frequency, then (with the for loop from the post I linked), check if the count of each item is equal or smaller than the minimial frequency and if it is, change the minimal frequency to m (count) – ttb Jun 21 '17 at 08:32

1 Answers1

0

You should initialize your var with a bigger value :

var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var mif = 99999999999999;
var m = 0;
var itemin;
for (var i = 0; i < arr1.length; i++) {
  for (var j = 0; j < arr1.length; j++) {
    if (arr1[i] == arr1[j])
      m++;
  }
  if (mif > m) {
    mif = m;
    itemin = arr1[i];
  }
  console.log(arr1[i] + ' exist ' + m + ' times in array');
  m = 0;
}
console.log('item less frequent : ' + itemin);
Rylyn
  • 333
  • 3
  • 10