(Java) Statistical analysis assignment - java

I'm currently working on a program designed to perform some statistical analysis. Specifically, I want it to store some random integers (say 10, between min and max inclusive) in an array, compute the min, max, mode, and a few other values through separate methods, and give the user a menu with which to either choose a method (and loop back to the menu, if they do so) or exit.
My biggest problems right now are that the main program requires two inputs to carry out any method (doesn't do anything after putting in the first), and also that each method returns 0 or 0.0.
Here is my code:
import java.util.Random;
public class Stats extends Main
{
int sampleSize;
double count;
double ave;
double sum;
int min;
int max;
int mode;
int evenCount;
int oddCount;
int countMatching;
//Constructor: use an RNG to generate sampleSize integers between minValue and maxValue. Store the numbers in an array named 'data'.
public Stats()
{
sampleSize = 10;
data = new int[sampleSize];
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
return;
}
//Method: return the sample set's max value
public int getMax()
{
max = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] > max)
max = data[i];
}
return max;
}
//Method: return the min value
public int getMin()
{
min = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] < min)
min = data[i];
}
return min;
}
//Method: return the average value
public double getAve()
{
count = sampleSize;
sum = 0;
for(int i = 0; i < sampleSize; i++)
{
sum = sum + data[i];
}
ave = sum / count;
return ave;
}
//Method: return the mode; in case of a tie, choose the smallest value
public int getMode()
{
int popularity1 = 0;
int popularity2 = 0;
int array_item;
for(int i = 0; i < sampleSize; i++)
{
array_item = data[i];
for(int j = 0; j < sampleSize; j++)
{
if(array_item == data[j])
popularity1++;
}
if(popularity1 >= popularity2)
{
mode = array_item;
popularity2 = popularity1;
}
}
return mode;
}
//Method: return the count of even numbers
public int getEven()
{
int evenCount = 0;
for (int i = 0; i < sampleSize; i++)
{
if (data[i] % 2 == 0)
evenCount++;
}
return evenCount;
}
//Method: return the count of odd numbers
public int getOdd()
{
int oddCount = 0;
for (int i = 0; i < sampleSize; i++)
{
if (data[i] % 2 != 0)
oddCount++;
}
return oddCount;
}
//Display all numbers, formatted in columns (hint: pg. 158)
public void displaySampleSet()
{
for (int i = 0; i < sampleSize; i++)
{
}
}
//Return the count of numbers in the sample set that match the input parameter
public int countMatching(int match)
{
int countMatching = 0;
return match;
}
//Create a list of private variable(s) that belong to the Stats class
private int[] data;
}
And here is the main program:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int input;
int stats;
Scanner keyboard = new Scanner(System.in);
Stats g = new Stats();
System.out.println("Welcome to the Stats Program!");
System.out.println();
System.out.println("Main Menu");
System.out.println();
System.out.println("1) Get max value");
System.out.println("2) Get min value");
System.out.println("3) Get the mean");
System.out.println("4) Get the mode");
System.out.println("5) Get the count of even numbers");
System.out.println("6) Get the count of odd numbers");
System.out.println("7) Display the sample set");
System.out.println("8) Return the count of numbers in the sample set that match the input parameter");
System.out.println("9) Exit");
System.out.println();
stats = keyboard.nextInt();
while (stats != 9)
{
if (stats == 1)
{
g.getMax();
input=keyboard.nextInt();
System.out.println("Max is: " + g.getMax());
}
else if (stats == 2)
{
g.getMin();
input=keyboard.nextInt();
System.out.println("Min is: " + g.getMin());
}
else if (stats == 3)
{
g.getAve();
input=keyboard.nextInt();
System.out.println("Mean is: " + g.getAve());
}
else if (stats == 4)
{
g.getMode();
input=keyboard.nextInt();
System.out.println("Mode is: " +g.getMode());
}
else if (stats == 5)
{
g.getEven();
}
else if (stats == 6)
{
g.getOdd();
}
else if (stats == 7)
{
g.displaySampleSet();
}
else if (stats == 8)
System.out.println("");
System.out.println("View other stats?");
System.out.println("");
System.out.println("1) Max 2) Min 3) Mean 4) Mode 5) Count of evens 6) Count of odds 7) Sample set numbers 8) Count of numbers that match input parameter 9) Exit");
stats = keyboard.nextInt();
}
System.out.println("Thank you for using the Stats Program. See you next time!");
}
}
Both programs are incomplete, but I'm still getting values for each method (after two inputs), loops after they execute, and the exit works as intended.
Any tips or parts that are glaringly wrong/missing? I'd really like to understand this.
Thanks in advance!

When you create a Stats, the data array is immediately initialised in the constructor using the max and min fields. But these are zero at this point (because you leave them blank, and Java initialises blank int declarations to zero). You then call your random number generator:
data[i] = rand.nextInt((max - min + 1) + min);
min and max are zero, so this evaluates to:
data[i] = rand.nextInt(1);
and Random.nextInt() returns values up to, but not including, the input (see the docs).
So your 'random' data will always be zeros; therefore the minimum, maximum and average will also be zero.

Related

Finding the smith number between given range

I will get to the point quickly. Basically smith numbers are: Composite number the sum of whose digits is the sum of the digits of its prime factors (excluding 1). (The primes are excluded since they trivially satisfy this condition). One example of a Smith number is the beast number 666=2·3·3·37, since 6+6+6=2+3+3+(3+7)=18.
what i've tried:
In a for loop first i get the sum of the current number's(i) digits
In same loop i try to get the sum of the number's prime factors digits.
I've made another method to check if current number that is going to proccessed in for loop is prime or not,if its prime it will be excluded
But my code is seems to not working can you guys help out?
public static void main(String[] args) {
smithInrange(1, 50);
}
public static void smithInrange(int start_val, int end_val) {
for (int i = start_val; i < end_val; i++) {
if(!isPrime(i)) { //since we banned prime numbers from this process i don't include them
int for_digit_sum = i, digit = 0, digit_sum = 0, for_factor_purpose = i, smith_sum = 0;
int first = 0, second = 0, last = 0;
// System.out.println("current number is" + i);
while (for_digit_sum > 0) { // in this while loop i get the sum of current number's digits
digit = for_digit_sum % 10;
digit_sum += digit;
for_digit_sum /= 10;
}
// System.out.println("digit sum is"+digit_sum);
while (for_factor_purpose % 2 == 0) { // i divide the current number to 2 until it became an odd number
first += 2;
for_factor_purpose /= 2;
}
// System.out.println("the first sum is " + first);
for (int j = 3; j < Math.sqrt(for_factor_purpose); j += 2) {
while (for_factor_purpose % j == 0) { // this while loop is for getting the digit sum of every prime
// factor that j has
int inner_digit = 0, inner_temp = j, inner_digit_sum = 0;
while (inner_temp > 0) {
inner_digit = inner_temp % 10;
second += inner_digit;
inner_temp /= 10;
}
// System.out.println("the second sum is " + second);
for_factor_purpose /= j;
}
}
int last_temp = for_factor_purpose, last_digit = 0, last_digit_sum = 0;
if (for_factor_purpose > 2) {
while (last_temp > 0) {
last_digit = last_temp % 10;
last += last_digit;
last_temp /= 10;
}
// System.out.println("last is " + last);
}
smith_sum = first + second + last;
// System.out.println("smith num is "+ smith_sum);
// System.out.println(smith_sum);
if (smith_sum == digit_sum) {
System.out.println("the num founded is" + i);
}
}
}
}
public static boolean isPrime(int i) {
int sqrt = (int) Math.sqrt(i) + 1;
for (int k = 2; k < sqrt; k++) {
if (i % k == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
the output is:
the num founded is4
the num founded is9
the num founded is22
the num founded is25
the num founded is27
the num founded is49
how ever the smith number between this range(1 and 50) are:
4, 22 and 27
edit:I_ve found the problem which is :
Math.sqrt(for_factor_purpose) it seems i should add 1 to it to eliminate square numbers. Thanks to you guys i've see sthe solution on other perspectives.
Keep coding!
Main loop for printing Smith numbers.
for (int i = 3; i < 10000; i++) {
if (isSmith(i)) {
System.out.println(i + " is a Smith number.");
}
}
The test method to determine if the supplied number is a Smith number. The list of primes is only increased if the last prime is smaller in magnitude than the number under test.
static boolean isSmith(int v) {
int sum = 0;
int save = v;
int lastPrime = primes.get(primes.size() - 1);
if (lastPrime < v) {
genPrimes(v);
}
outer:
for (int p : primes) {
while (save > 1) {
if (save % p != 0) {
continue outer;
}
sum += sumOfDigits(p);
save /= p;
}
break;
}
return sum == sumOfDigits(v) && !primes.contains(v);
}
Helper method to sum the digits of a number.
static int sumOfDigits(int i) {
return String.valueOf(i).chars().map(c -> c - '0').sum();
}
And the prime generator. It uses the list as it is created to determine if a given
number is a prime.
static List<Integer> primes = new ArrayList<>(List.of(2, 3));
static void genPrimes(int max) {
int next = primes.get(primes.size() - 1);
outer:
while (next <= max) {
next += 2;
for (int p : primes) {
if (next % p == 0) {
continue outer;
}
if (p * p > next) {
break;
}
}
primes.add(next);
}
}
}
I do not want to spoil the answer finding, but just some simpler code snippets,
making everything simpler, and more readable.
public boolean isSmith(int a) {
if (a < 2) return false;
int factor = findDivisor(a);
if (factor == a) return false;
int sum = digitSum(a);
// loop:
a /= factor;
sum -= digitSum(factor);
...
}
boolean isPrime(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return false;
}
}
return true;
}
int findDivisor(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return i;
}
}
return a;
}
int digitSum(int a) {
if (a < 10) {
return a;
}
int digit = a % 10;
int rest = a / 10;
return digit + digitSum(rest);
}
As you see integer division 23 / 10 == 2, and modulo (remainder) %: 23 % 10 == 3 can simplify things.
Instead of isPrime, finding factor(s) is more logical. In fact the best solution is not using findDivisor, but immediately find all factors
int factorsSum = 0;
int factorsCount = 0;
for(int i = 2; i*i <= a; i++) {
while (a % i == 0) {
factorsSum += digitSum(i);
a /= i;
factorsCount++;
}
}
// The remaining factor >= sqrt(original a) must be a prime.
// (It cannot contain smaller factors.)
factorsSum += digitSum(a);
factorsCount++;
Here is the code. If you need further help, please let me know. The code is pretty self explanatory and a decent bit was taken from your code but if you need me to explain it let me know.
In short, I created methods to check if a number is a smith number and then checked each int in the range.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(smithInRange)
}
public int factor;
public boolean smithInRange(int a, int b){
for (int i=Math.min(a,b);i<=Math.max(a,b);i++) if(isSmith(i)) return true;
return false;
}
public boolean isSmith(int a){
if(a<2) return false;
if(isPrime(a)) return false;
int digits=0;
int factors=0;
String x=a+¨" ";
for(int i=0;i<x.length()-1;i++) digits+= Integer.parseInt(x.substring(i,i+1));
ArrayList<Integer> pF = new ArrayList<Integer>();
pF.add(a);
while(!aIsPrime(pF)){
int num = pF.get(pF.size-1)
pF.remove(pF.size()-1);
pF.add(factor);
pF.add(num/factor)
}
for(int i: pF){
if((factors+"").length()==1)factors+= i;
else{
String ss= i+" ";
int nums=0;
for(int j=0;j<ss.length()-1;j++){
nums+=Integer.parseInt(ss.substring(j,j+1));
}
}
}
return (factors==digits);
}
public boolean isPrime(int a){
for(int i=2;i<=(int)Math.sqrt(a),i++){
String s = (double)a/(double)i+"";
if(s.substring(s.length()-2).equals(".0")){
return false;
factor = i;
}
}
return true;
}
public boolean aIsPrime(ArrayList<int> a){
for(int i: a) if (!isPrime(a)) return false;
return true;
}
}

Recursion Coin Change

Need help figuring out how to print the individual coins such as quarters = 3, pennies = 1, instead of just giving me 4 coins for 76 cents. I tried setting 4 counters, but that just repeatedly printed out the coin names and answers were wrong.
import java.util.Scanner;
public class Money
{
public static void main(String args[])
{
int[] coins = { 1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4)
{
if (sum <= 0 || coins.length == 0)
{
return 0;
}
for (int i = coins.length - 1; i >= 0; i--)
{
if(coins[i] == 1 && coins[i] != 5)
{
counter1++;
}
if(coins[i] == 5)
{
counter2++;
}
if(coins[i] == 10)
{
counter3++;
}
if(coins[i] == 25)
{
counter4++;
}
if (coins[i] <= sum)
{
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
Try this:
import java.util.Scanner;
public class Money
{
public static void main(String[] args) {
int[] coins = {1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4) {
if (sum <= 0 || coins.length == 0) {
return 0;
}
for (int i = coins.length - 1; i >= 0; i--) {
if (coins[i] == 25 && sum >= coins[i]) {
counter4++;
}
else if (coins[i] == 10 && sum >= coins[i]) {
counter3++;
}
else if (coins[i] == 5 && sum >= coins[i]) {
counter2++;
}
else if (coins[i] == 1 && sum >= coins[i]) {
counter1++;
}
if (coins[i] <= sum) {
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
I suspect you have misunderstood how arguments passed to Java methods work. You are passing in the 'counter' values and then iterating them inside the method and expecting their values in the calling method to have changed. That's not how Java works. See here for more details.
If you're not expecting to get the values back from the method (because you're printing them inside) then there's no point making them arguments. Best to make it a local variable inside the scope of the method.
You might find it a bit easier if you order from largest to smallest and return an array from your change calculator. Then you won't need individual variables for your counters.
Something like the following:
int[] coins = {25, 10, 5, 1};
String[] names = {"Quarters", "Dimes", "Nickles", "Pennies"};
int[] change = getChange(coins, total);
for (int i = 0; i < change.length; i++) {
System.out.println(names[i] + ":" + change[i]);
}
private int[] getChange(int[] coins, int total) {
int[] result = new int[coins.length];
for (int i = 0; i < coins.length; i++) {
result[i] = total / coins[i];
total -= result[i] * coins[i];
}
return result;
}
Note that this takes advantage of Java's integer division rounding down. So if you start with 76 cents it will return 3 quarters (76/25 -> 3). Note also that the second statement in the loop could be total %= coins[i] which would have the same effect but might be more understandable. Either way the code is saying 'remove from the total the value of the current denomination`.

Beginning Java - Creating a successful binary search algorithm

Design an application that has an array of at least 20 integers. It should call a module that uses the sequential search algorithm to locate one of the values. The module should keep a count of the number of comparisons it makes until it finds the value. Then the program should call another module that uses the binary search algorithm to locate the same value. It should also keep a count of the number of comparisons it makes. Display these values on the screen.
I already have the sequential search working properly, and it displays the number of iterations it took to find the desired value. However, I am having trouble with my binary search module. Every time it searches for a value, it always returns the value 1. Here is the code I have excluding the sequential search module.
Appreciate any help.
//Scanner class
import java.util.Scanner;
public class JavaProgramCh9Ex7_test {
//global scanner to read input
static Scanner keyboard = new Scanner(System.in);
//size of array
final static int SIZE = 20;
//main
public static void main(String[] args) {
//populate the array
int [] twentyNumbers = new int [SIZE];
populateTwentyNumbersArray(twentyNumbers);
//sort the numbers using bubble sorting:
bubbleSort(twentyNumbers);
displayTwentyNumbersSorted(twentyNumbers);
//ask the user for a value to search for:
int desiredValue = getValidInteger("Search for a number", 1, 20);
//start the binary search algorithm:
int binSearchComparison = performBinarySearch (twentyNumbers, desiredValue);
System.out.println(binSearchComparison);
}
//Display the 20 integers in the array in ascending-order:
public static void displayTwentyNumbersSorted (int [] numArray){
System.out.println("");
System.out.println("Here are the 20 numbers sorted in ascending-order");
for (int i = 0; i < numArray.length; i++) {
if(i < 19){
System.err.print(numArray[i] + ", ");
}
else{
System.err.print(numArray[i]);
}
}
}
//Perform the binary search for the user's desired value:
public static int performBinarySearch (int [] numArray, int userValue){
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = -1;
boolean found = false;
for (int i = 0; i < numArray.length; i++) {
while ((!found) && (first <= last)) {
middle = ((first + last) / 2);
if (numArray [middle] == userValue) {
found = true;
iteration = (i + 1);
}
if(numArray [middle] > userValue) {
last = (middle - 1);
}
if(numArray [middle] < userValue) {
first = (middle + 1);
}
}
}
return iteration;
}
//Populate the array with 20 random integers:
public static void populateTwentyNumbersArray (int [] numArray){
int number = 0;
for (int i = 0; i < numArray.length; i++) {
do{
number = getRandomNumber(1, 20);
}while (checkNum(numArray, number));
numArray[i] = number;
}
}
//Check to make sure the number is unique:
public static boolean checkNum (int [] numArray, int num) {
boolean value = false;
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == num) {
value = true;
}
}
return value;
}
//Sort the array in ascending order
public static void bubbleSort(int [] numArray){
int temp;
int maxElement;
for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
for(int i = 0; i <= (maxElement - 1); i++){
if(numArray[i] > numArray[i + 1]){
temp = numArray[i];
numArray[i] = numArray[i + 1];
numArray[i + 1] = temp;
}
}
}
}
//Get a valid Integer from the user to determine the number of seats sold per section:
public static int getValidInteger(String msg, int low, int high) {
int newValue = getInteger(msg);
//Check that the user entered a valid number within the range:
while (newValue < low || newValue > high) {
System.err.println("Please enter a number from " + low + " to " + high + ".");
newValue = getInteger(msg);
}
return newValue;
}
//Check for a valid Integer input from the user:
public static int getInteger(String msg) {
System.out.println(msg);
while (!keyboard.hasNextInt()) {
keyboard.nextLine();
System.err.println("Invalid integer. Please try again.");
}
int number = keyboard.nextInt();
keyboard.nextLine(); //flushes the buffer
return number;
}
//Get a random number to represent the computer's choice:
public static int getRandomNumber(int low, int high){
return (int)(Math.random() * ((high + 1) - low)) + low;
}
}
In your performBinarySearch you check for the all values of array, this maximizes the binary search complexity, though the loop hasn't any effect on searching. If the value present in the array, then the searching function checks whether it is present or not when i=0 and make found=true. After that the inner while loop don't executes as found=true all the times.
For that reason, iterator=(i+1) for i=0 all the times if the value is present in the array, otherwise iterator=-1.
Consider the below performBinarySearch function :
public static int performBinarySearch(int[] numArray, int userValue) {
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = 0;
boolean found = false;
while ((!found) && (first <= last)) {
iteration++;
middle = ((first + last) / 2);
if (numArray[middle] == userValue) {
found = true;
break;
}
if (numArray[middle] > userValue) {
last = (middle - 1);
}
if (numArray[middle] < userValue) {
first = (middle + 1);
}
}
if (found) return iteration;
else return -1;
}
Here, I have reused your code with a simple modification. I have deleted your redundant outer loop and calculated the number of iteration each time the while loop executes. If found then make found=true and break the loop(as I have already found the expected value) and return the value.

How to find a specific number from a user set upperbound and lowerbound in java

The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories