import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Queuessorting {
public static int randInt(int min, int max) {
// Usually this should be a field rather than a method variable so
// that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
ArrayList<Integer> ar = new ArrayList<Integer>();
ArrayList<Integer> temp = new ArrayList<Integer>();
ArrayList<Integer> arf = new ArrayList<Integer>();
System.out.println("Enter n: ");
int n = myScanner.nextInt();
int count = 0;
int r=0;
for(int i = 0;i < n;i++){
ar.add(randInt(1,99));
}
System.out.println(ar.size());
for(int i=0;i<ar.size();i++)
System.out.println(ar.get(i));
int j=0;
int nctr=0;
while(ar.size() > 0){
int a = 0;
int nct = 0;
a = ar.remove(0);
if(nctr == 0){
temp.add(a);
}
else{
if(arf.size() != 0){
for(int k = 0;k<arf.size();k++){
temp.add(arf.remove(0));
}
}
while(r<temp.size() && count == 0) {
if(a > temp.get(r)){
arf.add(a);
count++;
nct++;
}
else
arf.add(temp.remove(0));
r++;
}
if(nct == 0)
arf.add(a);
}
if(temp.size()!=0){
for(int l = 0;l<temp.size();l++){
arf.add(temp.remove(0));
}
}
nctr++;
}
System.out.println("***************************");
for(int u=0;u<arf.size();u++)
System.out.println(arf.get(u));
}
}
My code works perfectly fine when having an input of 2 but if I enter any number greater than 2 the sorting is completely messed up. I'am sorting descending order being the top the number the first index of the arraylist
pseudocode: example : 72,97,2 a will get 72 from ar then store it to temp because it is the first one, next a will get 97 and compare it to 72 if a > 72, a will go to arf then the remaining values in temp will go to arf too : 92,72 <- contents of arf now. After that procedure everything in arf will go to temp and the loop goes on and on I hope you understand my explanation :(
the final output or the final arf contents will be 97,72,2
Related
When user enter number 1 smaller than number 2 swap does not work,
but when number 1 is larger than number 2 it works. I don't understand why this is occurring. I would appreciate some suggestions or help.
package javaapplication36;
public class JavaApplication36 {
static Scanner s = new Scanner(System.in);
// main method
public static void main(String[] args) {
int[] arr = new int[10];
input(arr);
System.out.println("Enter n1 :");
int n1 = s.nextInt();
System.out.println("Enter n2 : ");
int n2 = s.nextInt();
display(arr);
int temp = 0;
int index_a = index(arr, n1);
int index_b = index(arr, n2);
if (index(arr, n1) != -1 && index(arr, n2) != -1) {
temp = arr[index_a];
arr[index_a] = arr[index_b];
arr[index_b] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void display(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void input(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter number : " + (i + 1));
arr[i] = s.nextInt();
}
}
public static int index(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n)
return i;
}
return -1;
}
}
I tried this and could not find anything wrong. To make debugging this easier I recommend you populate your array using random numbers.
Create an instance of Random
Random rand = new Random();
And assign the output to your array variable.
arr = rand.ints(10,1,15).toArray();
The arguments to rand.ints are.
10 - the number of elements
1 - the start of the range of numbers
15 - the end of the range (not including that number)
So that call would generate 10 numbers from 1 to 14 inclusive.
One possibility for any problems could be duplicate numbers in your array and finding the correct one to swap. But I was unable to reproduce the error.
I've completed Hackerrank's "Birthday Cake Candles" challenge and have passed 6 out of 8 test cases using the following code that sorts an array, then increments the frequency that the max int occurs and prints that value:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numCandles = in.nextInt();
int height[] = new int[numCandles];
for(int height_i=0; height_i < numCandles; height_i++){
height[height_i] = in.nextInt();
}
//Option 2: Sort the array, then count the number that are highest.
Arrays.sort(height);
int max = height[height.length - 1];
int index = height.length - 1;
int freq = 0;
while(height[index] == max) {
freq++;
index--;
}
System.out.println(freq);
}
}
It's not passing Test Case #6 (input) or Test Case #7. In short, Test Case #6 is 100,000 occurrences of the int 999999 and Test Case #7 is 100,000 occurrences of the int 1. Expected output for both is supposed to be 100000.
I'm thinking it might be encountering a runtime error because of the sorting method I call on the array and the array trying to sort ints of equal value over and over? Can anyone explain why my code won't work for those two Test Cases?
When all values in the input are the same, as in the sample input you included, the condition in this loop will be true until index is reduced to -1, at which point you'll get an ArrayIndexOutOfBoundsException:
while(height[index] == max) {
freq++;
index--;
}
Add a range check to the loop condition, for example:
while (index >= 0 && height[index] == max) {
With this change, the solution will pass all tests. But it's an inefficient solution. You sorted the input to reduce the number of iterations in the while loop. But sorting is an O(n log(n)) operation, which is slower than a simple filtering with O(n). For example:
int numCandles = in.nextInt();
int heights[] = new int[numCandles];
int m = Integer.MIN_VALUE;
for (int i = 0; i < numCandles; i++) {
heights[i] = in.nextInt();
m = Math.max(m, heights[i]);
}
final int max = m;
long freq = IntStream.of(heights).filter(x -> x == max).count();
System.out.println(freq);
You are getting an outbound of exception because you are reaching a part when you go less than 0
while(height[index] == max) {
freq++;
if(index == 0)
break;
index--;
}
This is my solution for this problem
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int height[] = new int[n];
for(int height_i=0; height_i < n; height_i++){
height[height_i] = in.nextInt();
}
Arrays.sort(height);
int counter = 0;
int different = height[n-1];
for(int height_i=n-1; height_i >=0 ; height_i--){
if(different ==height[height_i] )
{
counter = counter + 1;
}
else
{
break;
}
}
System.out.println(counter);
}
This is my solution for this. I think is better to use a for than a while for this.
Simple Solution
static int birthdayCakeCandles(int[] arr) {
int max = arr[0];
int count = 0;
for(int i =0; i<arr.length;i++) {
if(max < arr[i]) {
max = arr[i];
}
}
for(int i =0; i<arr.length;i++) {
if(max == arr[i]) {
count++;
}
}
return count;
}
my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}
import java.util.Scanner;
public class People
{
public static final Scanner keyboard = new Scanner(System.in);
static final int Max= 50;
public static void main(String[]args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("Please enter value:");
int [] peopleTypes = new int[Max];
for(index=0; index<Max; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
So basically I have to create a code that allows a user to input 50 values (1,2,3,4) into a array and count how many of each was inputted and outputs that. I am stuck on creating the code to count the inputted values. I am new to array and am not sure if I'm on the right path.
Actually you don't need to store the input, take a (closer) look at a possible solution:
import java.util.Scanner;
public class People {
static final Scanner keyboard = new Scanner(System.in);
static final int MAX = 50;
static final String[] LABLES = {"infants", "children", "teens", "adults"};
public static void main(String[] args) {
int[] counts = new int[4];
for (int i = 0; i < MAX; i++) {
System.out.println("Please enter value:");
int current = keyboard.nextInt(); //problem input: "abc" -> java.util.InputMismatchException
while (current > 4 || current < 1) {//checks range
System.out.println("Please enter a valid value (between 1 and 4):");
current = keyboard.nextInt();//...and repeat
}
counts[current - 1]++;//increment counter, "current - 1", since 0-based array and 1-based input
}
System.out.println("Evaluation finished!");
for (int i = 0; i < 4; i++) {//print the output
System.out.println(LABLES[i] + ": " + counts[i]);
}
}
}
I maybe misunderstanding the context but I do not see the need for creating a peopleTypesArray. My understanding is that all you need is a count or teens , adults etc from a list of 50 people, so just keep incrementing the individual counters and display them outside the loop. Something like:
for(int i = 0 ; i < 50; i++){
int peopleType = keyBoard.nextInt();
if(peopleType == 0){
infantCount++;
}
---- and so on
}
System.ou.println(" infant = " + infantCount);
--- and so on
I tried to create a simple lottery program. Here is a problem: it still prints same numbers. For example I got 33 21 8 29 21 10 as output. Everytime when random number is generated, code checks if that number is already generated, then it creates a new random number but after that it doesn't check again. I couldn't find a way to do that.
public static void main(String[] args)
{
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++)
{
randomNum = (int) (Math.random() * 50); //Random number created here.
for (int x = 0; x < i; x++)
{
if (lottery[i] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);//If random number is same, another number generated.
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
There are 2 problems with your code:
you check if lottery[i] and randomNum are the same, it should be lottery[x]
when you re-generate a random number, you don't check it against the first numbers in lottery.
Here is a corrected version:
public static void main(String[] args) {
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
You are changing the random number while you are checking it. You need to pick one random number and check whether it is present or not.
BTW A shorter approach is to use a shuffle.
// give me all the number 1 to 50
List<Integer> list = IntStream.range(1, 51).boxed().collect(Collectors.toList());
// shuffle them.
Collections.shuffle(list);
// give me the first 6
System.out.println(list.subList(0, 6));
A simple solution, between the first (who could be very abstract for a not Java programmer) and the 2nd (not assuring the unicity of the number list).
Collection<Integer> liste = new ArrayList<Integer>();
for (int i = 0; i < 6; i++)
{
Boolean ap = false;
while (!ap)
{
Integer randomNumber = (int) (Math.random() * 50);
if (! liste.contains(randomNumber)){
liste.add(randomNumber);
ap = true;
}
}
}
for (Integer liste1 : liste) {
System.out.print(liste1+" ");
}
try this one, it creates 12 x (6 out of 45)
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
for (int i = 0; i < 12; i++){
Integer[] tipp = new Integer[6];
int n = 0;
do {
int r = random.nextInt(45) + 1;
if (Arrays.asList(tipp).indexOf(r)<0){
tipp[n]= r;
n++;
}
} while (n<=5);
Arrays.sort(tipp);
System.out.println(Arrays.toString(tipp));
}
}
public static void main(String[] arg) {
int[] lottery = new int[6];
int randomNum;
c1:
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
if(randomNum == 0) {
continue c1;
}
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum ) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
This is the object class for making a ticket, it will create ONE ticket with ascending values at which whatever parameters you choose. This program won't run until you have a main method that you call. Make sure to import TreeSet.
import java.util.TreeSet;
public class TicketMaker{
private int numbersPerTicket;
private int lowestNumber;
private int highestNumber;
TicketMaker(){
numbersPerTicket=0;
lowestNumber=0;
highestNumber=0;
}
TicketMaker(int numbersPerTicket,int lowestNumber,int highestNumber){
if(numbersPerTicket > 0 && lowestNumber >= 0 && highestNumber >= lowestNumber){
this.numbersPerTicket=numbersPerTicket;
this.lowestNumber=lowestNumber;
this.highestNumber=highestNumber;
}
}
public boolean printTicket(int numbersPerTicket,int lowestNumber,int highestNumber){
if(numbersPerTicket > 0 && lowestNumber >= 0 && highestNumber >= lowestNumber){
if(numbersPerTicket > highestNumber){
System.out.println("Error not in-bounds");
return false;
}
int rand;
int count=0;
System.out.println("[Ticket Printed]");
TreeSet<Integer> set = new TreeSet<>();
do{
rand = (int)(Math.random()*highestNumber)+lowestNumber;
set.add(rand);
count++;
}while(set.size() != numbersPerTicket);
System.out.println(set);
return true;
}
else{
System.out.println("Error not in-bounds");
return false;
}
}
public boolean isValidTicketData(int numbers,int lowest,int highest){
if(lowest != 1){
if(highest == numbers)
return false;
}
if(numbers <= highest){
if(numbers > 0 && lowest >= 0 && highest >= lowest)
return true;
}
return false;
}
}