You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
basically ye ek probablitry ka question hai isme har index par us index ki weightage yani aane kitni bar aayega ye diya hua hai. ham ise 2 tarike se kar sakte hai pahle ki ek array bnaye or usme jitni weightage
6
+
hai utni bar wo number dal de and uske bad random function se ek random number generate kare arr.length
7
+
ke range me and us index par rakaha number return kar de lekin isme bahut space lag sakta hai even ye array ke capacity se bahar bhi ja sakta hai isliye ise implement av nahi karenge;
8
+
9
+
10
+
2
11
+
Soln 2;
12
+
ek naya array bnaye jo same size ka hoga lekin element uske piche tak ke weightage ka sum hoga and ab ek
13
+
random number generate karenge jo 0 to sum ke barabar hoga ab random number jis range me aayege us range ko
14
+
return kar denge;
15
+
*/
16
+
17
+
// creating an array reference to store their sum array
18
+
intarr[];
19
+
intsum=0;
20
+
publicSolution(int[] w) {
21
+
// creating array
22
+
arr = newint[w.length];
23
+
for(inti=0;i<arr.length;i++){
24
+
// calculating sum
25
+
sum= sum +w[i];
26
+
// storing sum values in the array
27
+
arr[i] = sum;
28
+
}
29
+
30
+
}
31
+
32
+
publicintpickIndex() {
33
+
// generating random number : in java it is double and return b/w 0-1 so we will multiply by sum to get
34
+
// in or range and typecast it
35
+
intnum = (int)(sum * Math.random());
36
+
// now searching the random number and returning the index
37
+
for(inti=0;i<arr.length;i++){
38
+
if(num<arr[i])
39
+
returni;
40
+
}
41
+
// not come here
42
+
return -1;
43
+
44
+
}
45
+
}
46
+
47
+
/**
48
+
* Your Solution object will be instantiated and called as such:
0 commit comments