Converts an array of integer values into a cumulative histogram. - Java java.lang

Java examples for java.lang:Math Convert

Description

Converts an array of integer values into a cumulative histogram.

Demo Code

/*/*w w w. j  a v  a  2 s  . c om*/
 * Image conversion utilities.
 * 
 * Copyright (c) 2006 Jean-Sebastien Senecal (js@drone.ws)
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA.
 */
//package com.java2s;

import java.util.Arrays;

public class Main {
    /**
     * Converts an array of integer values into a cumulative histogram.
     * @param array an integer array.
     * @param histogram keeps the cumulative frequencies of values in the 
     *    <code>array</code> in the range (0, length of <code>histogram</code>).
     */
    public static void arrayToHistogram(int[] array, float[] histogram) {
        Arrays.fill(histogram, 0);

        int totalPoints = 0;
        for (int v : array) {
            if (v > 0 && v < histogram.length) {
                histogram[v]++;
                totalPoints++;
            }
        }

        for (int i = 1; i < histogram.length; i++)
            histogram[i] += histogram[i - 1];

        if (totalPoints > 0) {
            for (int i = 1; i < histogram.length; i++)
                histogram[i] = (totalPoints - histogram[i])
                        / (float) totalPoints;
        }
    }

    /**
     * Converts an array of short values into a cumulative histogram.
     * @param array a short array.
     * @param histogram keeps the cumulative frequencies of values in the 
     *    <code>array</code> in the range (0, length of <code>histogram</code>).
     */
    public static void arrayToHistogram(short[] array, float[] histogram) {
        Arrays.fill(histogram, 0);

        int totalPoints = 0;
        for (short a : array) {
            int v = a & 0x0000ffff;
            if (v > 0 && v < histogram.length) {
                histogram[v]++;
                totalPoints++;
            }
        }

        for (int i = 1; i < histogram.length; i++)
            histogram[i] += histogram[i - 1];

        if (totalPoints > 0) {
            for (int i = 1; i < histogram.length; i++)
                histogram[i] = (totalPoints - histogram[i])
                        / (float) totalPoints;
        }
    }
}

Related Tutorials