I tried to sort an array accending and count the array elements
please help me find whats missing, have debugged many times. here is my code and the output i got. Thanks
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;
System.out.println("Enter the integers between 1 and 100" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}
calling the function here
Sorting(num, i, count);
}
public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;
for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}
System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}
Here is the output:
run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. Later on out of the first 6 numbers all are 0 so the output you have is correct.
To aviod the problem you face I suggest you use ArrayList instead of simple array so that you can add elements dynamically to it.
Try this
The counting method
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
Then use
int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}
This works for sure.
You are doing a bit more work than is necessary. I would solve this like so:
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for( i=0; i<num.length; i++){
int current = input.nextInt();
if(countMap.get(current) != null)
{
int incrementMe = countMap.get(current);
countMap.put(current,++incrementMe);
}
else
{
countMap.put(input.nextInt(),1);
}
}
Related
I wanted to check if frequency of minimum element is odd: I would print lucky, otherwise print "Unlucky".
I used a technique related to counting sort arr[arr1[i]]++ counting duplicated as value and reference to the actual value to it's INDEX. I tried with this but it didn't bring the correct answer [appreciate if you correct my code rather than a new different solution]
input: 6 6 6 4 4 4 4 3 3 3 7 7
output: Unlucky
since the minimum frequency is 7, 7%2!=0 so Unlucky
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t-->0) { //Test cases
int n=in.nextInt();//array's length
int arr[]=new int[n];// array
for(int i=0;i<arr.length;i++) {
arr[i]=in.nextInt();
}
int counter[]=new int[256];//counting duplicates
for(int i=0;i<arr.length;i++) {
counter[arr[i]]++;
}
int min=1;
int pos=0;
for(int i=0;i<counter.length;i++) {
if(counter[i]<min && counter[i]!=0) { //search for minimal frequency (counter[i]!=0 since our counter array could easily have lot zeroes
min=counter[i];
pos=i;
}
}
System.out.println((pos%2==0)?"Unlucky":"Lucky");
}
}
There is no need to the while loop and other loop for counter, you assign the array using n variable,
then you enter values to the arr and check frequency in the same loop.
And select the min frequency to check if it's lucky or not
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();// array's length
int arr[] = new int[n];// array
int counter[] = new int[n];
int min = 1;
int pos = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
counter[arr[i]]++;
if (counter[i] < min && counter[i] != 0) {
min = counter[i];
pos = i;
}
}
System.out.println((pos % 2 == 0) ? "Unlucky" : "Lucky");
in.close();
}
, input
12 6 6 6 4 4 4 4 3 3 3 7 7
, output
Unlucky
Consider the following points:
Your program is less useful/efficient for three reasons: (A) It will work for integers from 0 to 255 only (B) You are using a fixed size array of size 256 which means that even if the user enters just a few numbers, it will consume space for 256 integers (C) You are iterating the loop 256 times to calculate the frequency even if the user enters just a few numbers.
There are so many ways to count the frequency of numbers. Commonly people use a Map to do so. I've used the same thing in the function, minFrequencyNumber shown below:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int n = in.nextInt();
int arr[] = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
System.out.println("The number with minimum frequency is: " + minFrequencyNumber(arr));
System.out.println((minFrequencyNumber(arr) % 2 == 0) ? "Unlucky" : "Lucky");
}
public static int minFrequencyNumber(int[] arr) {
Map<Integer, Integer> m = new HashMap<>();
// Iterate the array
for (int i : arr) {
// If the number does not exist in the Map, put the number as the key and 1 as
// the value (frequency); otherwise, put the number as the key in the map by
// increasing its value (frequency) by 1
m.put(i, m.getOrDefault(i, 0) + 1);
}
int num = 0, minFrequency = Integer.MAX_VALUE;
// Iterate the map
for (Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() < minFrequency) {
minFrequency = e.getValue();
// Store the key (the number) whose frequency is minimum
num = e.getKey();
}
}
return num;
}
}
A sample run:
Enter the size of array: 12
Enter 12 integers: 6 6 6 4 4 4 4 3 3 3 7 7
The number with minimum frequency is: 7
Lucky
public static void checkMultiple(int a[]){
//will use this count variable later
//int[] count = new int[10];
//first scan over the array
for (int i = 0; i < a.length; i++)
{
//seeded loop to check against 1st loop
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
System.out.print(a[i] + " ");
}
}
}
}
I'm having trouble counting repeated numbers in an integer array of 10 random numbers. I havent wrote the "count" function yet but the checkMultiple() will print out the numbers that are repeated. However, some of the time it prints correctly such as:
4 2 9 0 9 6 3 3 7 5
9 3
the first line being the whole array and the second the numbers that are repeated at least once in the array. But when there is more than two of a single integer, it counts every single one of that integer such as:
9 5 2 8 5 5 7 6 3 3
5 5 5 3
Any tips or advice would be much appreciated!
It looks like as you are looping through and then immediately outputting the results.
This prevents the program from comparing what's being currently parsed and what has already been been parsed and counted.
I would pass an empty array into the first FOR loop and instead of "System.out.print," store the number in the passed-in array. You can then compare the values that have already been parsed against the value currently being parsed to see if it has already been counted.
When the outside FOR loop exits, output the array that was originally passed in empty (and now has a record of every duplicate in the initial array)
You are counting the number of duplicate instances. Your second example has three pairs of duplicate 5's. That's why you see the 5 repeated three times. Only output unique duplicate results.
Just use a hash map, if the key does not exist add it to the map with the value 1, if it does increase the value, then print the hash map.
A single iteration of the array will solve the problem.
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (counter.containsKey(a[i])) {
counter.put(a[i], counter.get(a[i]) + 1);
} else {
counter.put(a[i], 1);
}
}
Iterator it = counter.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
for (int i = 0; i < pair.getValue(); ++i) {
System.out.print(pair.getKey() + " ");
}
// or you could just print the number and how many times it was found
System.out.println(pair.getKey() + " " + pair.getValue());
it.remove();
}
try this
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class BirthdayCake {
private static void printcake(int n,int[] arr){
//Map<Integer,Integer> ha = new HashMap<Integer,Integer>();
int temp = arr[0],max=0, count=0;
/*for(int i=1;i<n;i++){
max = arr[i];
if(max<=temp){
temp=max;
count++;
break;
}
else{
max = arr[i];
count++;
break;
}
}*/
Arrays.sort(arr);
for(int i:arr){
System.out.println(i);
}
System.out.println("max:" +max);
max = arr[arr.length-1];
for(int i=0;i<n;i++){
if(arr[i]==max){
count++;
}
}
System.out.println("count:" +count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Entere thye array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
printcake(n,arr);
}
}
I have an assignment they ask me to re-arrange an array from the even numbers to the odd numbers
like this:
Sample Output:
Please enter array of 5 integers:
1 2 5 6 4
the array after re-arranging:
2 6 4 1 5
I couldn't do it " I cant use methods" can anyone help me ?
this is my code:
public static void evenOdd(int[] arr){
int i=0;
int arr1[] = new int[5];
for (i=0;i<5;i++)
{
if (arr[i]%2==0)
arr1[i]=arr[i];
}
for (i=0;i<5;i++){
if(arr[i]%2!=0)
arr1[i]=arr[i];
}//end for
for(i=0;i<5;i++)
System.out.print(arr1[i]+" ");
System.out.println("");
}//end method
THANK YOU
The problem is when you add them into the new array you are putting them in the same position: i. Use a separate int to keep count of what part of the index you are on.
public static void evenOdd(int[] arr){
int i=0;
int count = 0;
int arr1[] = new int[5];
for (i=0;i<5;i++) {
if (arr[i]%2==0) {
arr1[count]=arr[i];
count++;
}
}
for (i=0;i<5;i++){
if(arr[i]%2!=0) {
arr1[count]=arr[i];
count++;
}
}//end for
for(i=0; i < 5; i++) {
System.out.print(arr1[i]+"\n");
}
}//end method
Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.