I have run into a little problem. I have a homework exercise where i need to 'randomly' select a string from a string array. The goal of the exercise is to make a code which choses a random (inserted) name. My code:
public void run() {
int userSelection = -1;
int userAmount = 0;
String[] users = new String[userAmount];
int[] amountChosen = new int[userAmount];
while (userSelection != 0) {
drawMenu();
System.out.println();
//user selecting the menu choice
System.out.print("Make a selection from the menu: ");
userSelection = userInput();
System.out.println();
//forcing the user to give one of the allowed values
while (userSelection < 0 || userSelection > 4) {
System.out.print("That is invalid input. try again: ");
userSelection = userInput();
}
//adding users
if (userSelection == 1) {
System.out.print("How many users do we have?");
userAmount = userInput();
users = new String[userAmount];
amountChosen = new int[userAmount];
addUsers(users, userAmount); //returns user array with names
System.out.println();
}
//selecting random user
else if (userSelection == 2) {
int playerSelect = (int) (Math.random()*userAmount);
amountChosen[playerSelect]++;
System.out.println(users[playerSelect] + " was chosen!");
System.out.println();
}
//display the amount the users were chosen
else{
System.out.println("******** Turns ********");
for (int i = 0; i < userAmount; i++){
System.out.println("* " + "[" + amountChosen[i] + "] " + users[i]);
}
System.out.println("***********************");
System.out.println();
}
}
}
As you can see i now have a totally random userselection. For keeping tabs on how often a player is chosen i already made the 'int[] amountChosen' array. The goal is to "select a random player, also make it chose the player that is chosen the fewest times" so basicly it needs to select the string with the lowest amountChosen. (Also: I am aware my code may be a little bit messy and weird in some places. I just started learning java)
Thank you for response!
I won't give out the answer to your assignment. But, here is a naive implementation of what you are trying to achieve:
private void someMethod() {
String[] strArray = {"foo", "bar", "foobar"};
Random random = new Random();
System.out.println(strArray[random.nextInt(strArray.length)]);
}
Explanation:
You take a random number between 0 and the length of your string array using Random and then just use this as an index to query your string array.
If I understand correctly, you want to pick randomly one of all players having the lowest amount chosen?
Use a Map<String, Integer> with the amounts;
Filter the map with all players with the lowest amount;
Use Random.nextInt(amountOfLowest).
You could use Java Streams.
Hints: • use map.entrySet().stream() to stream over the map elements • use values(), unboxed() and min() to get the lowest value • use filter(), map() and collect() to collect a list of all players with the lowest amount • use List.get(new Random().nextInt(...)) to select a player.
Related
I am doing this assignment for my CSCI 1301 class and i'm kinda stuck.
The assignment is to write a program that will provide a list of services to users and allow them to choose any or all services they would like and display the final price.
Here's my code so far,
public static void carMaintenance()
{
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.next();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
System.out.println("What services whould you like for your "+makeOfCar+"?");
System.out.println(services[0]+", "+services[1]+", "+services[2]+", "+services[3]+".");
}
Where i'm stuck at is how would I go about allowing the user to request as many services they want?(Logically speaking, they can only request up to 4 services)
I figured I could use another array and put it in a "do-while" loop to achieve this but then, once I check it against the "services" array how would I assign a price to each service the user requested so that I can calculate the total price for all requested services?
any insight and help is greatly appreciated!
You could keep track of the sum in an extra variable. So your idea with the extra array to check for duplicates would still work. Check if the service is already chosen and if not, add the chosen index to the sum.
public static void carMaintenance() {
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.nextLine();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
double sum = 0;
System.out.println("What services whould you like for your " + makeOfCar + "?");
System.out.println(services[0] + ", " + services[1] + ", " + services[2] + ", " + services[3] + ".");
String choice;
//This array simply tracks true or false for chosen/not chosen. boolean arrays are initialized with all values false.
boolean[] chosenServices = new boolean[services.length]; //Can only be as many elements as there are services. This way you don't have to change it when you add another service
do {
choice = sc.nextLine();
int choiceIndex = getIndex(services, choice);
if (choiceIndex < 0) break; //Choice doesn't exist. You will have to refine that and add messages
if (!chosenServices[choiceIndex]) { //service not yet chosen
chosenServices[choiceIndex] = true;
sum += prices[choiceIndex];
} else {
System.out.println("Was already chosen!");
}
} while (!choice.toLowerCase().equals("exit")); //Or something similar
System.out.printf("%.2f", sum); //Price with 2 digits
}
public static int getIndex(String[] arr, String search) {
for (int i=0; i<arr.length; i++) {
if (search.equals(arr[i]))
return i;
}
return -1;
}
As mentioned in one of the comments, this is only a rough implementation. You might want to do this with index input from the user, you might want to check for false inputs more precise than I did here etc. but that should do what I think you mean.
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result
Hi I have been trying to figure this quiz out
A lottery company shares out prizes to winning contestants every week. Most weeks, more than one contestant wins, in which case they try to share out the prizes as fairly as possible. Their prize distribution office has hired you to write a program that they will use to distribute prizes in the fairest way possible.
The program you write should take two lines of input:
A comma-separated list of this week's prizes' values
A comma-separated names of this week's winners
For example, the input could be:
100,800,200,500,400,1000
Joshua,Mahesh,Lilian
The program should then output the fairest possible distribution of prizes, by displaying one line for each winner, with the values of the prizes allocated to them. For example, given the input above, the output could be:
Joshua:100,400,500
Mahesh:1000
Lilian:800,200
The example above gives a perfect solution, where all winners get the same value of prizes (total value of 1000 each). In many cases, this will not be possible, but all prizes must be distributed and cannot be divided. Part of your job is to decide how you define 'fair' for these cases. For example, given the input
400,400,500,600
Barry,Sheila,Onyango,Wekesa
The following would be acceptable output, because there is no fairer distribution possible:
Barry:400
Sheila:400
Onyango:500
Wekesa:600
I am using java and so far this is what I have come up with
import java.util.Scanner;
import java.util.Arrays;
public class Main {
private static String amounts;
private static String names;
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print(
"Please enter the lottery amounts separated by commas: ");
if (userInput.hasNext()) {
amounts = userInput.next();
// System.out.println("You entered: " + amounts);
}
System.out.print("Please enter the contestants names: ");
if (userInput.hasNext()) {
names = userInput.next();
// System.out.println("You entered: " + names);
}
String amountArray[] = amounts.split(",");
String nameArray[] = names.split(",");
award(nameArray, amountArray);
}
// Method that awards the amounts to the winners
public static void award(String names[], String amounts[]) {
int randomAmount;
int randomName;
for (int i = 0; i < amounts.length; i++) {
randomAmount = (int) (Math.random() * amounts.length);
int usedValue[] = new int[amounts.length];
usedValue[i] = randomAmount;
if (checkValueUsed(randomAmount, usedValue)) {
randomName = (int) (Math.random() * names.length);
int usedName[] = new int[names.length];
System.out.println(names[randomName] + " = "
+ amounts[randomAmount]);
} else {
break;
}
}
}
private static boolean checkValueUsed(int currentState, int[] myArray) {
boolean found = false;
for (int i = 0; !found && (i < myArray.length); i++) {
if (myArray[i] == currentState) {
found = true;
}
}
return found;
}
private void checkUsedValue(int currentState, int[] myArray) {
for (int i = 0; (i < myArray.length); i++) {
if (myArray[i] == currentState) {
}
}
}
}
My idea of fair is to select a random amount and assign it to a random winner.
1) This looks like an interview/exam question. I'm not to judge but... really?
2) Your idea of fair is NOT what is intended. By the examples given, fair means all prizes are distributed and each winners total is as close to each other as possible.
3) From the above - this is a known problem. A greedy algorithm is likely to perform well. (I can't really see why not, unless you get very specific on the optimization part of the problem)
For a "fair" distribution you could try something like this:
Randomly order the winners.
For each winner, assign them the current highest available prize; so using your first example, winner one gets 1000, winner two gets 800, winner three gets 500.
If there are prizes left to distribute, for all but the first winner, assign them the current highest available prize that doesn't take them above the prize total of the first winner; winner two would get 200 (matching the 1000 of winner one), winner three gets 400 (to make 900).
Repeat step three until there are no more prizes or no prizes have been allocated; winner three gets 100 to match the 1000 of the other two.
If there are still prizes to allocate, sort the winners in descending order based on total prizes, and start allocating the lowest available prizes to all but the first winner.
Repeat step five until all prizes are allocated.
//My problem is that in the method canceledOrder the string [] waitingList[] is not being seen at least that is what I think.
public static String[] canceledOrder(String[] waitingList,String[] waitingList1,String []waitingList2,String[] waitingList3){//I've decided to pass these string [] hoping the string from the other methods will now be seen in canceledOrder();
Scanner in = new Scanner (System.in);
int option;
System.out.println("Select the event you want to cancel :\n");
events();
option= in.nextInt();
in.nextLine();
System.out.println("Person on wait list is " + waitingList[name] );
switch (option){
case 1:
System.out.println("Please enter your name:\n");
canceledname = in.nextLine();
System.out.println("name:" + canceledname);
for (String s : myStringList) {
if(s.equals(canceledname)){
s = waitingList[name];
System.out.println("The new name is\n" + s);
name++;
}
return s; // I want it to now return waitingList[name]
}
break;
I may be wrong, but did you want to loop through the arraylist to see if any values in the list equal cancelledName?
If so, you may want something like this
for (String s : myStringList) {
if(s.equals(canceledname)){
k = waitingList[name];
System.out.println("The new name is" + k);
name++;
}
}
Edit: with possible solution to problem
// declare array of Attendees, capacity is 20
// I would rather use ArrayList, but it seems you're trying to use array
String attendees[] = new String[20];
// delcare wait list
String waitList[] = new String[2];
// declare int for tickets sold
int ticketsSold = 0;
// declare waitlist
int waitlistCount = 0;
// prompt buyers for purchase of tickets
// ticketsSold = ticketsSold + 1 or 2 depending on tickets
// if ticketsSold is 20 do not sell tickets and send to waiting list
// Do this until full
// if ticketsSold = 20
// prompt user to go on wait list
// if yes, ask how many tickets
// if tickets requested for waitlist exceeds current waitlist + tickets requested
// System.out.println("Sorry, waitlist is full");
// else prompt for user name
String name = in.nextLine();
waitlist[waitListCount] = name;
// here's the part I think you're having problems with
// if person is deleted from attendees
// get name of person not attending
int i = 0;
while (!cancelledName != attendees[i]) {
i++
}
// replace attendees index with waitlist Name
attendees[i] = waitlist[0];
// move the waitlist forward
waitlist[0] = waitlist[1];
waitlist[1] = null;
This is the best I can think of as far as logic. If you logic is sound and looks similar to mine, just focus on the bottom portion, where I think you're having the most problems
I guess you want to find out if canceledname exists in myStringList, for that you'll have to traverse myStringList - no way around it.
for(String name : myStringList){
if(name.equals(canceledname){
// continue...
k = waitingList[name];
System.out.println("The new name is" + k);
i++;
name++;
}
}
For that kind of comparison it would be better to save the names in a Set for example:
HashSet<String> names = new HashSet<String>();
// here you'll add the names to the hash-set
// using: names.add("whatever");
// ...
//and now:
if(names.get(canceledname) != null){
// continue ...
}
You cannot compare ArrayList to String, instead use contains method to find if element exists in the ArrayList.
boolean isElementExists = myStringList.contains(canceledname);
if(isElementExists) {
// other codes here
}
See the API: ArrayList#contains()
If my program gives the user about a team's championship history, for example, if the user enters Chelsea, my program will say, "They have won it in 2012,2010,2007,2008" (using parallel array list already provided and has to be used).
How would i display, from that result, the number of times they have won . So if that information is correct, i want my program to say, "Chelsea has won it 4 times".
This is what i have so far:
public static void showWinner(short years[], String winners[]){
Scanner kd = new Scanner (System.in);
String name;
System.out.println("Which teams result would you like to see?: " );
name = kd.next();
for (int i = 0; i < winners.length; i++) {
if (winners[i].equals(name)){
System.out.println(years[i]);
}
}
Try this: I am assuming that winners array and years array has mapping in which year which team won. I suggest you to use Map for this purpose. It will be more understandable and efficient.
int count = 0;
for (int i = 0; i < winners.length; i++){
if (winners[i].equals(name)){
count ++;
System.out.println(years[i]);
}
}
System.out.println(name + " has won it" + count + "times");