Tag Archives: array

Web

For loop through an associative array

assocarr
To go through an associative array or object, you could use:

<script type='text/javascript'>
/* <![CDATA[ */
var data = {};
data['var1'] = 'value1';
data['var2'] = 'value2';
data['var3'] = 'value3';
console.log(data);

for (var prop in data) {
  if (Object.prototype.hasOwnProperty.call(data, prop)) { 
    console.log("prop: " + prop + " value: " + data[prop])
  }
}
/* ]]> */
</script>

Finding the most common element in array

arrays
Here is another way to find the most common element in array.
Just for comparison with Fruz implementation http://fruzenshtein.com/exercise-1/

package com.firetrot.fruz;

import java.util.Arrays;

public class Fruz {

    public static void main(String[] args) {
        int[] arr = { 1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2 };
        System.out.println("Input:  " + Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("Sorted: " + Arrays.toString(arr));

        int valueName = arr[0];
        int valueCount = 1;

        int tmpCount = 1;
        for (int i = 1; i < arr.length; i++) {
            int prev = arr[i - 1];
            int curr = arr[i];

            // If equals - just increase counter
            if (curr == prev) {
                tmpCount++;
            }

            // If not equals or end of array - make processing
            if (curr != prev || i == arr.length - 1) {
                if (tmpCount > valueCount) {
                    valueName = prev;
                    valueCount = tmpCount;
                }
                // Reset counter
                tmpCount = 1;
            }
        }

        System.out.println("Name: " + valueName);
        System.out.println("Count: " + valueCount);
    }
}

The output:

Input: [1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2]
Sorted: [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 8, 9, 9]
Name: 3
Count: 6

The advantage is no need reason to hold a map of digit – count. So, less memory usage occurs.