Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Good evening
i'm trying to solve a question which is :
You are given a int[] marks containing the grades you have received so far in a class. Each
grade is between 0 and 10, inclusive. Assuming that you will receive a 10 on all future
assignments, determine the minimum number of future assignments that are needed for you to
receive a final grade of 10. You will receive a final grade of 10 if your average grade is 9.5 or
higher.
Definition Class: AimToTen Method: need Parameters:
int[] Returns: int Method signature: int need(int[]
marks) (be sure your method is public) Examples 1)
{9, 10, 10, 9} Returns: 0 Your average is already 9.5, so no
future assignments are needed. 2) {8, 9} Returns:
4 In this case you need 4 more assignments. With each
completed assignment, your average could increase to 9, 9.25, 9.4
and 9.5, respectively
My attempt to solve is :
public int need(int[] marks) {
int i=0, sum = 0, avg = 0, k = 0, counter = 0, ToCompleteMarks[] = null;
for (i; i < marks.length; i++) {
sum = sum + marks[i];
ToCompleteMarks[i] = marks[i] + ToCompleteMarks[i];// To copy the array so when i add 10 later to the program the original array does not change > good ?
}
avg = sum / marks.length;
while (avg < 9.5)
ToCompleteMarks[i]; //I need to add the number 10 to the array then get back to calculate the avg . But no ideas how to do that ! .
counter++;
return counter;
}
if you could help me with that I would be really greatful
thanks
We can do the below mentioned steps:
1. Get the difference between the avg calculated and the desired average(9.5)
LEts say that the calculated average is 8.
Difference would be 9.5-8 = 1.5
Hence we can take the upper limit(ceiling value) of the difference using Math.ceil(difference). Here it would be 2. Thus we need to add two assignments to the array.
Related
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 1 year ago.
Improve this question
I have an array of even number of elements, I have to select n/2( n=array size), pairs and calculate their GCD such that the sum of their GCD is max, given once we use those elements from array, we cannot use them again.
Example1: `
Input : 8 24 12 16
Output : 20
Explanation: We select two pairs (8,16) and (12,24) as sum of their GCD is maximum.
If we choose some other pairs, say (8,12) and (24,16), sum of their GCD will be 4+4 =8.
Example 2:
Input : 12 10 36 25 36 16
Output: 45
Explanation: We select the following 3 pairs : (36,36), (10,25) and (12,16) as the sum of their GCD is
36+5+4 = 45.
Our Approach:
for i in range(0,n):
max = 0;
for j in range(i+1,n):
temp = gcd(a[i], a[j]) // standard func to find GCD
if(max<temp):
store i and j
store max gcd every time and finally make a[i] and a[j] =0 to mark the visited elements
Edited
Constraint: max number of elements = 20, a[i]< 10^9.
Can you suggest an algorithm to optimally satisfy the above testcases in the least time complexity?
Because my approach is failing on multiple testcases.
This is a comment but I am not allowed to post comment yet.
It is not good to solve this problem by looking for the largest gcd.
Take [8,9,24,36], the largest gcd is gcd(24,36) = 12, that will get you gcd(24,36) + gcd(8,9) = 12+1 =13.
However, the largest sum is given by gcd(8,24) + gcd(9,36) = 8+9 = 17.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Question :
Given the number k, return the minimum number of Fibonacci numbers whose sum is equal to k, whether a Fibonacci number could be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 , for n > 2.
It is guaranteed that for the given constraints we can always find such fibonacci numbers that sum k.
Link to question:
https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/
Example :
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
class Solution {
public int findMinFibonacciNumbers(int count) {
PriorityQueue<Integer> num=new PriorityQueue<>(Collections.reverseOrder());
int i1=1,i2=1;
num.add(i1);
num.add(i2);
int k=count;
int i3=0;
k=k-2;
int res=0;
while(k>=1){
i3=i2+i1;
num.add(i3);
int temp=i2;
i2=i3;
i1=temp;
k--;
}
while(count!=0){
int n=num.poll();
if(n<=count)
{ res++;
count-=n;
}
}
return res;
}
}
It says wrong output for 'input=3'. I generated the fibonacci series and traversed from highest number to find numbers less than or equal to sum. It will be really helpful if somebody helps me.
Thank you in advance.
You can simply use recursion for this problem.
This'll pass through:
class Solution {
public int findMinFibonacciNumbers(int k) {
if (k < 2)
return k;
int first = 1;
int second = 1;
while (second <= k) {
second += first;
first = second - first;
}
return 1 + findMinFibonacciNumbers(k - first);
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
If you are preparing for interviews:
We would want to write bug-free and clean codes based on standards and conventions (e.g., c1, 2, c++1, 2, java1, 2, c#1, 2, python1, javascript1, go1, rust1). Overall, we would like to avoid anything that might become controversial for interviews.
There are also other similar platforms, which you might have to become familiar with, in case you'd be interviewing with specific companies that would use those platforms.
If you are practicing for contests1:
Just code as fast as you can, almost everything else is very trivial.
For easy questions, brute force algorithms usually get accepted. For interviews, brute force is less desired, especially if the question would be an easy level.
For medium and hard questions, about 90% of the time, brute force algorithms fail mostly with Time Limit Exceeded (TLE) and less with Memory Limit Exceeded (MLE) errors.
Contestants are ranked based on an algorithm explained here.
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
My job is to generate and urban residents using normal probability distribution.
Number of cities, 3000, Population 15 000 000
(in JAVA)
int people = 15000000;
int[] arrayofcity = new int[3000]
for (int i = 0; i < arrayofcity.length; i++) {
//how to generate people to the towns of total
//nextGaussian()??
}
Thank you for your help
Try something like this.. Not very efficient as the distributions are averaged/cancelled for every 2 values.
int people = 15000000;
int[] arrayofcity = new int[3000];
int sharedSpread=people/3000; // sharedSpread= avg population
for (int i = 0; i < arrayofcity.length; i++) {
if(i%2!=0)
arrayOfCity[i] = sharedSpread + (sharedSpread-arrayOfCity[i-1]);
else
{
Random r = new Random();
int val = Random.nextInt();
arrayOfCity[i] = val%sharedSpread ;
}
}
PS: This is not the exact code, but this can show how to go about the problem.. You can change the frequency of distribution . Instead of 2 here, we can change it to 4 to get better random distributions...
A rough sketch of a method:
Use Random#nextGaussian() to create a value X between 0-1 for each city.
Calculate the sum of all these X values. Call it S.
For each city, take its value X and divide by S. Multiply this result by the total population (15 000 000). This is how many people live in this city.
Note that this would be tricky to implement in practice due to rounding. As such, the total population may be slightly above/below the desired 15 000 000, so some method will be needed to add/remove the extra people.
One (non efficient, but beautiful mathematically IMO) way to do it is:
For each person (repeat 15M times), choose with uniform distribution
his city.
It will give you a total sum of 15M people in all cities, and according to central limit theorem - you will get close to normal distributionin in each city, because each city is basically a sum of Bernoulli trials with p=1/3000, over 15M trials.
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
My assignment is to make "Yahtzee" game on Java Program.
I am almost done except the Small Straight method. (Cannot figure it out.)
Small Straight is when the dice got 4 straight number. (Ex. 12334, 23345, 34556, and etc.)
Here is my code of isSmallStraight method (This code is not completed!):
public static boolean isSmallStraight(List<Die> dice) {
boolean result = false;
List<Die> copy = new ArrayList<Die>(dice);
Collections.sort(copy);
List<Die> testCase1 = new ArrayList<Die>();
testCase1.add(new Die(1));
testCase1.add(new Die(2));
testCase1.add(new Die(3));
if(copy.containsAll(testCase1)) {
result = true;
System.out.println(result);
}
return result;
}
What I want to do in here is I passed 5 random numbers of dice from the main method (List dice) and put them into the "copy" object.
Since I need to use java.util.List.containsAll() method(requirement), I think I need to make one other object "testCase1" to compare with "copy". (If you have other method to solve this question, it is fine at least you use java.util.containsAll() method.)
However, what I don't know right now is if I use dice.add(new Die(3)), it means the program picks random numbers from 1,2, and 3. (Not die number 3) - Also, it gave me compile-time error.
So, I want to know how I can store dice specific number 1,2,3, and 4 for "testCase1", 2,3,4, and 5 for "testCase2", and 3,4,5, and 6 for "testCase3" and use copy.containsAll(testCase1) becomes true.
Please help me as soon as possible!
PS. Die class is already programmed by my professor. (So, cannot change any in the Die class).
Put the numbers into a TreeSet to get rid of duplicates and get sorting for free.
You have 4 straight dice if:
The set contains exactly 4 numbers
The difference between the largest and the smallest is 3
The method I like to use (for large and small straights as well as all other scoring) is to create a new int array from the int array that holds the dice values. Like this:
int[] numDice = new int[6];
for (int i: diceValues)
numDice[i-1] += 1;
This counts up all your dice and puts the number of each, in order, in a new array. For instance, if the 5 dice you rolled were 3, 4, 3, 1, and 6, your new array would be {1, 0, 2, 1, 0, 1}, and a yahtzee of all 4s would turn into {0, 0, 0, 5, 0, 0}. From this new array it's fairly trivial to determine all of the scores. For straights:
int straightCount = 0;
for (int i: numDice) {
if (i > 0)
straightCount++;
else
straightCount = 0;
if (straightCount > 3)
smallStraight = true;
if (straightCount > 4)
largeStraight = true;
}
If you wanted to you could use this array to easily determine all the valid scores in one short method, and store the booleans in a single array.
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'm making a system.
What I want is, for every 6 items you have to buy 5 (so when the price is 5 each item, 6 items is not 30 but 25, same with 12, 18, 24 etc...)
How would I do that?
I thought it would be something like this:
if (amount % 6 == 0) {
}</code>
But that would get it one time if I'm correct.
The modulus operator won't work in this situation.
So for an efficient solution.
int numberOfItems = 17; //however many there are
int discount = numberOfItems / 6;
double priceToPay = price * (numOfItems - discount);
By having the discount as an int you won't get any rounding or decimal part after the division.
Using modulus will only give you the discount if you have 6, 12, etc. items. What about if you have 7 items? You won't get any discount (it is not divisible by 6)! So, it would be something like this:
int numOfItems = 6; //this will be different every time
//copy numOfItems because it will be modified
int temp = numOfItems;
double price = 5;
int discount = 0;
//While there are at least 6 items
while (temp >= 6) {
discount++; //discount one item
temp -= 6; //take away 6
}
//you have to pay for the number of items, but not the discounted items
double amountToPay = price * (numOfItems - discount);
This way, every time you take away 6, you don't have to pay for 1 item.