Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Having a bit of issue here:
Question(input): complete the function draftPick(). function takes two arguments: an array of integers teams representing the order of teams and how many spots they have to fill, and an integer i that determines which team in the order (zero-indexed) we want to know the last pick for.
Output: function should return an integer representing which player the ith team in the draft order (zero-indexed) will select with their last pick
Expected runtime: O(n)
sample input: lineArray = [5, 1, 2]
position = 2
sample output: 5
Explanation: call the tree teams A, B, C. The draft has team A picking first and trying to fill 5 roster spots, team B picking second and filling 1 roster spot, and team C picking last and filling 2 roster spots:
turn 1: A picks 1st best player
turn 2: B picks 2nd best player
turn 3: team C picks 3rd best player
turn 4: team A picks again and get 4th best player
turn 5: since team b has already filled all their roster spots, team C picks 5th best player (THUS THE ANSWER 5)
Attempt: trying to develop an algorithm - i see that the ith team for example in [5,1,2] this team has 2 spots to fill. we know that the order of play he picks depends on the number of players in the other elements. i tried traversing the array subtracting (-1) from each element from i=0 to i
Here's an algorithm that I made that suffices according to my testing:
int draftPick(int[] teams, int target) {
int targetTeam = teams[target];
int finalPick = 0;
for(int i = 0; i <= target; i++) {
int team = teams[i];
if(team > targetTeam) team = targetTeam;
finalPick += team;
}
for(int i = (target + 1); i < teams.length; i++) {
int team = teams[i];
if(team > targetTeam - 1) team = targetTeam - 1;
finalPick += team;
}
return finalPick;
}
Related
This question already has answers here:
How to create variables dynamically in Java? [closed]
(7 answers)
Closed 22 days ago.
Here's my problem: Let's say that I have an Object array of long length, in my case it's class Player. I set up some loop to traverse through Player[] and want to find all Player objects that meet my requirements. However, the amount of result is unknown before execution and I need to assign each of the candidate elements a unique name. How can I change/iterate those variable names being assigned while looping?
I recently just started learning about Java. Based on what I know so far the only solution to keep tracking them might be ArrayList or List?
Can someone help me find proper solutions?
Here I simplified my question in a scenario to expect only 2 candidate elements.
Player[] players; //this is a sorted array of players
int candidateNum = 0; //this is for keeping track of the amount
Player A;
Player B;
int index = players.length - 1;
...
while(candidateNum < 2) {
if (players[index].getLevel() > 10) {
Player A??? //what am I gonna do to name Player A?
//and how should I name Player B which is coming out within next several loops?
candidate++;
}
index--;
}
//furthermore, what about in a case that results' amount is unknown?
As already answered, variables must be known at compile time. Since you are restricted to use arrays, I'd use second array where you put those players who meet criteria, and give a name using a counter "top1, top2,"etc
// we'll put here those players that meet the criteria.
// since we do not know how many elements, set size at most same as original array
Player[] bestPlayers = new Player[players.length];
// let's rank the players
int candidate = 0;
for (Player player : players) {
if (player.getLevel() > 10) {
// assign a unique name
player.setName("Top " + candidate);
bestPlayers[candidate] = player;
// increase counter of best players
candidate++;
}
}
You can see a working example here:
https://www.sololearn.com/compiler-playground/c55gz69GE28O
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to generate a random double for this section of my assignment.
The question is
"Each week, each female Guppy who is 10 weeks old or older has a 25 percent chance of spawning".
I would like to generate a random double to determine if each female Guppy should spawn or not.
My code so far:
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
//?
}
I don't see any reason to generate a random double according to your question. What you need is an integer ranging from 0 to 3 inclusive where each number account for 25% for the spawning.
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
// Generate a random integer in [0,3]
// Since there is a 25% or 1/4 chance
if(Math.abs(r.nextInt()) % 4 == 1){
//Note that the 1 in the condition can be replaced by any
// integer in [0,3]
//Put spawning code here
}
}
Check out this link for more information on random:
Random (Java Platform SE 7
To generate a random double, you can look at this question, however, this problem can more easily be solved by generating random ints.
In your situation, generating an int between 0 to 3 is what you want because checking if it is 0 will be true 25% of the time (1 Value / 4 Possible values = 25%).
EDIT: If you would like to also generate a random number to see how many spawn a Guppy will have use threadLocalRandomInstance.nextInt(int bound); like before.
These constraints can be translated to code like this:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
ThreadLocalRandom tlr = ThreadLocalRandom.current();
int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1.
int spawn;
if(num == 0) {
spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1.
} else spawn = 0;
System.out.println("This guppy had " + spawn + " spawn.");
}
}
I use ThreadLocalRandom as it is more straightforward as supported by this answer.
If you are not using Java 1.7+, use Random#nextInt(int) instead as also shown by that answer.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been trying to fix my snakes and ladders code. For example if Player1's position on the gameboard is 98 and he rolls a 5 Player1's position should be 97. So,(100-98=2,(5-2)=3,100-3=97). I ahve been trying to implement this into my code in the possiblity that either player1 or player2 roll higher than 100.
MY CODE:
System.out.println (player1+" Rolled a " + P1Roll );
System.out.println (player2+" Rolled a " + P2Roll);
//If player1 position is greater than 100
if(P1Position+P1Roll>100){
P1=100-P1Position;
difference=P1Position-P1Roll;
P1Position=100-difference;
}
//If palyer2 position is greater than 100
else if(P2Position+P2Roll>100){
P2 = 100-P2Position;
difference=P2Position-P2Roll;
P2Position=100-difference;
}
System.out.println ("------------------------------------------------------------------------");
//calculate player positions
P1Position = P1Position + P1Roll;
P2Position = P2Position + P2Roll;
//call position methods
P1Position = Player1(P1Position, P1Roll, snakes, ladder, arrow);
P2Position = Player2(P2Position, P2Roll, snakes, ladder, arrow);
//Print out players current positions
System.out.println("==========================================================================");
System.out.println (player1+" is currently on square " + P1Position);
System.out.println (player2+" is currently on square " + P2Position);
System.out.println("==========================================================================");
According to your calculation it should be
difference=P1Roll-P1;
And for player 2:
difference=P2Roll-P2;
And try this more simple way for all cases:
P1Position = 100 - Math.abs(P1Position + P1Roll - 100);
Try removing the else after player 1, unless the methods are called after 1 player rolls.
(Another way of saying it: do both players roll, then you move them? If yes, remove the else. If player 1 rolls, and then you update, then keep the else. I don't see anything else wrong otherwise).
The else statement is treating the conditionals as such: "Is player 1's position plus roll greater than 100? If so, do this block, and that's it. If player 1's position plus roll is NOT greater than 100, try the next block". So, if player 1 does have to be "manipulated" using the if block, player two may never get the move to happen.
I hope my answer is not too confusing.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to learn how to make a poker game, so i searched around websites for poker projects.
This is the deck class i found.
This is the part of the code that make no sense to me.
int index_1, index_2;
for (int i = 0; i < 100; i++) {
index_1 = generator.nextInt(cards.size() - 1);
index_2 = generator.nextInt(cards.size() - 1);
temp = cards.get(index_2);
cards.set(index_2, cards.get(index_1));
cards.set(index_1, temp);
}
}
Looks like a random shuffle of the deck, picks two card positions at random. The nextInt(cards.size() - 1) will generate a random index in [0,cards.size() - 1) range:
index_1 = generator.nextInt(cards.size() - 1);
index_2 = generator.nextInt(cards.size() - 1);
swap the two cards, since you have to replace one of the cards first and you don't want to lose that object, the code uses temp to hold the first card to be replaced, cards.get(index_2) will obtain the first card object.
temp = cards.get(index_2);
The first set will replace the object in index_2 will the object from index_1 and the second set will replace the object in index_1 with the temporary object we stored earlier:
cards.set(index_2, cards.get(index_1));
cards.set(index_1, temp);
It does this procedure 100 times:
for (int i = 0; i < 100; i++)
If we assume cards.size() - 1 is the index of the last card in the deck, the nextInt call will skip the last card though, hard to know if that was intentional without more context.
What this code is doing is it's swapping two cards in the deck. It does this 100 times arbitrarily. A better way to do this is to randomly assign a card to a position in a deck. The way it is right now may never touch certain groups of cards and you may end up with a clump of cards in the same order as before in the same position. Plus it would only involve 52 moves instead of 300 (card2 -> temp, card1 -> card2, temp -> card1 ).
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Disclaimer: This is not a homework problem. I stumbled upon this puzzle here and I also have the answer. However, I am not able to figure out an approach to arrive at the solution.
The puzzle is as given below:
The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?
The answer happens to be 2,4,6,12.
Please suggest a way to solve this problem programmatically.
In Python (Which is not what you asked, but you're more asking for an algorithm):
import operator
import itertools
possible_ages = range(2,15)
# If the list of ages passed to this function returns true, then this solves the puzzle.
def valid(ages):
product_of_ages = reduce(operator.mul, ages, 1)
square_of_sum_of_ages = reduce(operator.add, ages, 0) ** 2
return product_of_ages == square_of_sum_of_ages
for number_of_children in range(1, 9):
for ages in itertools.combinations(possible_ages, number_of_children):
if valid(ages):
print ages
And that prints, almost immediately:
(2, 4, 6, 12)
You don't specify that the ages are all integers, but I'm going to assume that's true. If so, there are only about 1e9 possible combinations of those ages among 8 children. Simply enumerate (for(age1=2; age1<15; age1++) { for(age2=2; age2<15; age2++) { ...) them all and test. Your computer should finish that task within a few minutes even in a script interpreter.
There are optimizations to be applied, because hard-coding "8" loops is clumsy, and because the age lists are order-independent (having children of "4 and 2" is the same thing as "2 and 4"), but frankly I don't think that's worth it here. Your time taken coding the extra steps will take more time than you'll save at runtime.
I solved it in java using a recursive approach.
First the program prints all the combinations, then gives the correct combination (that matches the specified criteria) at last.
This program instantly gives the output
(2, 4, 6, 12)
just as you have specified in your question.
public class Tackle {
static int[] ages = {2,3,4,5,6,7,8,9,10,11,12,13,14}; // Since the program uses a recursive function,
static StringBuffer sb = new StringBuffer(""); // the variables are declared as static
static int x=0,occurances=0;
static int sum,pdt=1,count=0;
static String[] instances = new String[100];
static void recurse(int a[], int k, int n) throws Exception
{
if(k==n) // This program obtains various combinations using binary technique
{
for(int i=0;i<n;i++)
if(a[i] == 1){
System.out.print(ages[i]+" "); // Displays all the combinations available
sum = sum + ages[i];
pdt = pdt * ages[i];
count++;
sb.append(String.valueOf(ages[i]+" "));
}
if(Math.pow(sum, 2) == pdt && count<8){ // Checking the criteria
instances[occurances++] = sb.toString();
}
sb = new StringBuffer("");
count = 0;
sum = 0;
pdt = 1;
System.out.println("");
}
else for(int i=0;i<=1;i++)
{
a[x++] = i;
recurse(a,k+1,n);
x--;
}
}
public static void main(String[] args) throws Exception {
int[] a = new int[10000];
recurse(a,0,ages.length);
if(occurances>0)
{
System.out.println("No of combinations matching: " + occurances);
for(int i=0;i<occurances;i++)
System.out.println("The combination of ages is [ " + instances[i] + "]");
}
else
System.out.println("No combination matches the criteria. ");
}
}
The output obtained was
[All possible combinations are listed here]
No of combinations matching: 1
The combination of ages is [ 2 4 6 12 ]