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.
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 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
Actually, this question was asked one of the interviews, I do not know the exact answer, could you explain in detail ?
How would you select 100 random lines from a file with a 1 million
lines? Can`t read file into memory.
Typically, in such scenarios, you do not know the number of items in the input file in advance (and you want to avoid requiring two passes over your data, to check the number of available items first). In that case the solution proposed by #radoh and others, where you will create indices to select from, will not work.
In such cases, you can use reservoir sampling: You only need to know the number of items you want to select (k as follows) and you iterate over the input data (S[1..n]). Below is the pseudocode taken from Wikipedia, I'll leave it to your practice to convert this into a working Java method (the method would typically look something like List<X> sample(Stream<X> data, int k)):
/*
S has items to sample, R will contain the result
*/
ReservoirSample(S[1..n], R[1..k])
// fill the reservoir array
for i = 1 to k
R[i] := S[i]
// replace elements with gradually decreasing probability
for i = k+1 to n
j := random(1, i) // important: inclusive range
if j <= k
R[j] := S[i]
Note that although the code mentions n explicitly (i.e. the number of input items), you do not need to know that value prior to computation. You can simply iterate over an Iterator or Stream (representing lines from a file in your case) and only need to keep the result array or collection R in memory. You can even sample a continuous stream, and at each point in time (at least, as soon, as you've seen k samples) you have k randomly chosen items.
Generate the 100 random (unique) numbers (ranging from 0..1000000-1) into a list and then go through the file reading the lines with indexes from the list. Ideally, the list of numbers should be a Set.
Pseudocode:
int i = 0;
List<String> myLines = new ArrayList();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
if (myRandomNumbers.contains(i)) {
myLines.add(line);
}
i++;
}
Here's a pretty efficient way to do it:
Iterator<String> linesIter = ...
List<String> selectedLines = new ArrayList();
Random rng = new Random(seed);
int linesStillNeeded = 100;
int linesRemaining = 1000000;
while (linesStillNeeded > 0) {
String line = linesIter.next();
linesRemaining--;
if (rng.nextInt(linesRemaining) < linesStillNeeded) {
selectedLines.add(line);
linesStillNeeded--;
}
}
I haven't coded in Java in a while, so you might want to treat this as pseudo-code.
This algorithm is based on the fact that the probability that any given line (assuming we are uniformly selecting k distinct lines out of a total of n lines) will be contained in the collection with probability k/n. This follows from
1) the number collections of k distinct lines (out of n lines) is choose(n, k),
2) the number of collections of k distinct lines (out of n lines) which contain a particular line is choose(n-1, k-1), and
3) choose(n-1,k-1)/choose(n,k) = k/n
Note that k and n here correspond to linesStillNeeded and linesStillRemaining in the code respectively.
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.
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.