LeastFrequent - Output the integer which occurs least frequently along with its occurrence count from a list of 10 integers input from System.in. If multiple integers in the list occur least frequently, output any integer that occurs least frequently. Name your class LeastFrequent. You can assume that all 10 integers are in the range -100 to 100 inclusive.
import java.util.*;
public class LeastFrequent
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arr = new int[10];
int[] hold = new int[300];
int x = 0;
int count = 0;
int a = 1;
int least = 0;
System.out.print("numbers: ");
//adds 10 numbers to an array and counts occurrence
for(int i=0;i<arr.length;i++)
{
arr[i] = scan.nextInt();
hold[arr[i]]++;
}
for(int i=0;i<hold.length;i++)
{
if(hold[i] > 0)
{
}
}
System.out.println("least frequent: " + count + " occurs " + arr[count] + " times");
}
}
I have it asking the user for 10 integers and putting it into the array.
I also have it counting the occurrence of the input numbers and storing it in another array.
I am stuck on finding the least frequent one.
I know i need to scan through the second array again bu i dont know how.
Any thoughts on how to compare the element's values of the second array while skipping the values that equal 0?
Firstly, the following isn't quite correct:
hold[arr[i]]++
What would happen if I input -1?
As to finding the least occurring element, you need to find the smallest value in hold that's greater than zero. As you iterate over hold, you could keep track of the smallest such value seen so far as well as its index.
Finally, an alternative approach to the problem is to sort the array. Once you do this, equal values are brought next to each other. This simplifies counting the repetitions.
Related
Given a sorted list of integers, output the middle integer. A negative number indicates the end of the input (the negative number is not a part of the sorted list). Assume the number of integers is always odd.
Ex: If the input is:
2 3 4 8 11 -1
the output is:
Middle item: 4
The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers".
Hint: First read the data into an array. Then, based on the array's size, find the middle item.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userValues = new int[9]; // Set of data specified by the user
int middleItem;
/* Type your code here. */
for(int i=0; i<userValues.length; ++i){
while(userValues[i]>=0){
userValues[i] = scnr.nextInt();
}
}
if(userValues.length>8){
System.out.println("Too many numbers");
}
else{
middleItem = userValues[userValues.length/2];
System.out.println("Middle item: " + middleItem);
}
}
}
The main issue so far is finding a way to scan in fewer than the maximum allowed number of array items and having the loop stop when a negative number is entered. I've deleted the code to use negative integers as a sentinel value to focus on scanning and accepting fewer inputs. Any guidance would be appreciated.
You can read integers one by one and add them into a List, terminating when a negative number is entered, with a for loop.
List<Integer> numbers = new ArrayList<>();
for (int x; (x = scnr.nextInt()) >= 0;)
numbers.add(x);
System.out.println(numbers.get(numbers.size() / 2));
I'm trying to solve HackerRank Day Of Code 10.
In short, the task is to find the maximum number of consecutive 1's in the binary representation of a decimal number. In my code I've tried to use two variables: count and hold. count increases by 1 whenever the current position of the string and the previous position are both 1. Whenever the i'th position is 0, count 's value is assigned to the variable hold. In the following iterations if ever the value of count exceeds that of hold then the value of count is assigned to hold. In this way the maximum number of consecutive 1's is stored in hold. Finally I'm printing the value of hold.
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter decimal number");
int n = in.nextInt();
String binary = Integer.toString(n,2);
int count=1;
int hold=0;
if(binary.equals("0"))
System.out.println(0);
else
{
for(int i=0;i<binary.length();i++)
{
if(i==0){}
else if(binary.charAt(i-1)=='1' && binary.charAt(i)=='1')
{
count++;
}
if(count>hold)
hold=count;
if(binary.charAt(i)=='0')
{
hold=count;
count=1;
}
}
System.out.println(hold);
}
}
}
My code isn't working for the sample input "524275" which converts to "1111111111111110011" in binary. The output comes out to be 2 which is strange. my code is written such that the "maximum" number of consecutive 1's are returned. Where did I go wrong? I tried dry running the code mentally but can't spot the mistake yet.
After processing the first 15 ones in with the for loop, hold will actually have the value 15. Then you meet the first zero, and if(binary.charAt(i)=='0') { hold=count; count=1; } will reset count to 1. But then you immediately find another zero, and the same code if(binary.charAt(i)=='0') { hold=count; count=1; } stores 1 in hold and you loose the information 15.
An easy solution is just to remove the line hold=count; in this line. You already set hold three lines above. (And correctly, because you only do it if count is bigger then the previous best value.
The approach is quite complicated. If you want an easier approach. The code should be pretty self-explanatory.
int current_consecutive_ones = 0;
int best_consecutive_ones = 0;
for(int i = 0; i < binary.length(); i++)
{
if (binary.charAt(i) == '1')
current_consecutive_ones++;
else
current_consecutive_ones = 0;
if (current_consecutive_ones > best_consecutive_ones)
best_consecutive_ones = current_consecutive_ones;
}
System.out.println(best_consecutive_ones);
I have noticed when inputting an integer into an array that if the integer is larger than the arrays length it will throw an out of bounds exception. Why is this? Why can the array not accept any integer value? How can I correct this when I need to store integers larger than an arrays length.
Thank you!
Here is the code. When I enter an integer greater than 5 I get an out of bounds exception. If I enter integers less than 5 the code works perfectly.
public class NumOfOccur
{
static Scanner input = new Scanner(System.in);
static int[] cards = new int[5];
static int[] numOccurence = new int[5];
public static void main(String[] args)
{
System.out.println("Enter five values: ");
for (int i = 0; i < 5; i++)
{
System.out.print("Card " + (i + 1) + " : ");
cards[i] = input.nextInt();
}
containsPair(cards);
}
public static boolean containsPair(int hand[])
{
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
for (int i = 1; i < numOccurence.length; i++)
{
if (numOccurence[i] > 0)
System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");
}
return false;
}
}
What you are suggesting here is wrong. An array of integers can hold any integer. When you are storing an integer into an array (or any value for that matter) you have to make sure that the index you are inserting it into is valid.
For example
//perfectly valid
int[] foo = new int[1];
foo[0] = 500;
I suspect what you are doing is something like this.
//throws index out of bounds exception
int[] foo = new int[1];
foo[500] = 500;
Note the difference here. the number inside the [] on the left side of the assignment operator indicate the index you are working with.
Based on your now posted code, your problem is here:
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
To briefly explain what is going on.
1) you first initialize numOccurence to a length of 5 integers.
2) You are putting user input into the cards[] then you pass the cards array into into the function containsPair()
3) If the user enters a number greater than 5, lets say 7 the operation hands[i] would be 7. This would be the same as numOccurence[7] which is out of bounds
Without any code, I'm assuming you're just misunderstanding what you're doing with your array. You just have to make sure you're accessing a valid index. There's no restriction on what integer you can store in an integer array.
// Make an array of length ten
int[] myIntArray = new int[10];
System.out.println(myIntArray.length);
// Set the first value in the array to 99: perfectly legal
myIntArray[0] = 99;
System.out.println(myIntArray[0]);
// The following line throws ArrayIndexOutOfBoundsException
myIntArray[99] = 100; // The last index in the array is only 9, not 99!
System.out.println(myIntArray[99]); // This line would also crash, for the same reason
Having seen your code, I think the issue is with this:
First, your numOccurence array always has a length of 5, but in the line
numOccurence[hand[i]]++;
You will get the OutOfBoundsException if hand[i] is 5 or greater (meaning you typed in a value of 5 or greater).
To fix this you should either:
Put restrictions on what card values the user can enter
Make that line numOccurence[i]++ if you mean to keep track of the number of times each card position was drawn
Make numOccurence a longer array so it can store the number of times each possible card (e.g. 1 to 13 for Ace to King) has occured.
I'm definitely sure the question is wrong. You're saying this is not possible
int[] anArray = new int[10];
anArray[5] = 20;
Which is obviously not true.
If that's what you're saying, post your code, because you have a bug.
If you want to make your array larger or something, you should consider using an ArrayList or something similar. Post your code so we can help you.
This question already has answers here:
Random Number Generator: mainly how to stop repetition of numbers. Java
(6 answers)
Closed 9 years ago.
Ok so the objective is to generate 6 random numbers per line/row. With x number of rows (set by the user via UserInput). Each row MUST have unique numbers (non-duplicated numbers). I'm pretty sure the numbers are unique, however I can't seem to get it to have multiple rows, and I cannot figure out for the life of me what part is preventing multiple rows.
package rtg;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Array {
public static void main(String[] args) {
String name;
int noTickets;
int[] numbers = new int[6];
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
int ticketCount = 1;
System.out.println("Please input your name");
name = UserInput.readString();
System.out.println("Please input the number of tickets you want");
noTickets = UserInput.readInt();
System.out.println("___________________________________________\n___________________________________________");
System.out.println("___________________________________________\n___________________________________________");
System.out.println("Name: " +name+ "\nNumber of Tickets: " +noTickets+ "\nNumbers: ");
for (ticketCount = 1; ticketCount <= noTickets; ++ticketCount){
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
int i = 0;
for (Integer n : randomNumbers) {
numbers[i++] = n;
}
System.out.print( Arrays.toString(numbers) + "\n");
}
}
}
EDIT Thanks a lot everyone, I finally got there, turns out I put the array in the wrong place (it was outside the for loop so only made 1 set of random numbers) Fixed it now. Next challange; having a comparison program to scan 90+ sets of 6 unique numbers, and comparing if any of them match a different set (per row/set >.<)
You can stuff random integers into a Set<Integer> until it has six elements:
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
Alternatively, you can generate the numbers 1-50, shuffle them, and pick any six elements:
List<Integer> numbers = new ArrayList<>(50); // known capacity
for (int i = 1; i <= 50; ++i) { numbers.add(i); }
Collections.shuffle(numbers);
List<Integer> sixRandomNumbers = numbers.subList(0, 6);
The first solution does extra work whenever there is a collision; this extra work goes up the greater the ratio is of desired to total numbers. The second does extra work by having to deal with all 50 numbers; the extra work goes down the greater the ratio is of desired to total numbers. It's an interesting question where the cross-over point is.
EDIT (Responding to the edit to the original question) After you use one of the above methods to generate six distinct, random numbers, you need to put them into the variables you are going to use. One way (say, using the first method) is as follows:
int[] numbers = new int[6];
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
System.out.println("Six random numbers: " + randomNumbers.toString());
// if you need them as an `int` array:
int i = 0;
for (Integer n : randomNumbers) {
numbers[i++] = n;
}
The numbers array replaces your variables number1, ..., number6.
Use a data type which allows you to check if the int has already been created. For example, adding them to an ArrayList<Integer>.
ArrayList<Integer> numbers = new ArrayList<Integer>();
while(numbers.size() < 6) {
int num = rand.nextInt(50) + 1;
if(!numbers.contains(num)) {
numbers.add(num);
}
}
Of course, as #sanbhat says in the comments, you can use a Set<Integer> and avoid the if() conditional entirely in the loop. However I thought this would be more intuitive for a beginner who doesn't know that the Set API will not add a duplicate element.
Save a sorted list or more efficiently a set of the previously chosen values and check your current selection against the previous ones, if it was previously chosen try again.
If you know the valid range of your random numbers and if the size of that range is not prohibitive, one simple algorithm would be as follows:
Create an array with a size equal to your number range
Consecutively fill your array with the numbers in your number range
Iterate through the list an arbitrarily large number of times; generate two pseudorandom numbers that are within your array indices, and swap the two elements at those indices
After the iteration is complete, you will have an array of uniquely represented numbers that are all within your number range that appear in a random order. This nearly exactly simulates what happens when one shuffles a deck of cards.
You can then write a simple method to consecutively pop numbers out of your array each time it is called.
An advantage of this algorithm is that it can be implemented as an array of primitives, eg. int[], without any need for the Java Collections API.
I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)