Fill values X from values Y
I'm trying to create an algorithm to fill some values X (e.g. 10,000, 50,000, 100,000) from another set of values Y (e.g. 2500, 5000, 10,000, 42,500, 27,500).
Aim: To get the highest total filling of values X.
Rules: Can't repeat any value Y. Any value X must be entirely filled to count.
I've tried to knapsack this but it doesn't work very well because it creates huge value arrays. Any ideas?
Edit for more clarity:
An array of values X (ValueX), and an array of values Y (ValueY). Fill each individual value from ValueX, using any combination of values from ValueY. Once a value from ValueY has been used, it cannot be reused.
Example:
Fill ValueX[0] (10,000)
You could use ValueY[2] (10,000) and that would fill it completely. However now ValueY[2] cannot be reused for future filling of any ValueX.
If you then tried to fill ValueX[1] (50,000), you could use ValueY[3] (42,500), ValueY[1] (5000) and ValueY[0] (2500), to get a total of 50,000. Now those values(3, 1, 0) from ValueY have also been used.
See also questions close to this topic

Something wrong about ExecutorService#submit
public class CASTest { private static final int ii = 10; public static AtomicInteger ai = new AtomicInteger(); //public static CountDownLatch latch = new CountDownLatch(ii); public static void main(String[] args) { DemoRunnable dr = new DemoRunnable(); List<Future<AtomicInteger>> list = new ArrayList<Future<AtomicInteger>>(ii); ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < ii; i++) { list.add(es.submit(new Callable<AtomicInteger>() { @Override public AtomicInteger call() throws Exception { try { Thread.sleep(20); ai.incrementAndGet(); } catch (InterruptedException e) { e.printStackTrace(); } return ai; } })); } for (int i = 0; i < list.size(); i++) { try { System.out.println(list.get(i).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { es.shutdown(); } } } }
and the console print
I wanna the console print like this " 1 2 3 4 ... 10 " in order but why it acting like this?

How to stop child class to stop executing further line of code, if Parent Activity starts an intent
I have a base class that checks if app is launched from history, and no processes of app are available, then redirect user to
MainActivity
.This is my base class code;
public abstract class BaseActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { if(MainActivity.instance == null){ //instance is a static variable in MainActivity Intent i= new Intent(this, MainActivity.class); startActivity(i); this.finish(); return; }else{ setContentView(getLayoutRes()); } } //Child app override this method, and provides their layout. protected abstract int getLayoutRes();
Child Activity
public class MapActivity extends BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //1000 line of code } @Override protected int getLayoutRes() { return R.layout.activity_map; }
Now what it does when user launches the app from history, and no processes of the app are available, then it reads the check of
BaseActivity
and tries to start theMainActivity
intent, and does not set thelayout
,but the problem is that it does not stop there, it goes to
MapActivity
onCreate()
method and start executing the other lines of code, as i have not set layout, it crashes while trying to readfindViewById()
, it also fails at other static variables.So the whole point of redirecting user to
MainActivity
when the process is killed is not fullfiled.I need to know how to stop executing code of child class when
BaseClass
start the intent 
Make two thread plus an integer alternately
I write the code below in order to plus an integer
n
with two threads alternately untiln
reach toLIMIT
.Sometimes it works well, but in most of time it doesn't, and both
t1
&t2
are waiting.I'm a beginner for Java concurrent programming. Could anyone point out my bug? Thanks in advance :)
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class TwoThreads { private final int LIMIT = 500; private volatile int n = 0; public void runWithReentrantLock() { final ReentrantLock lock = new ReentrantLock(); final Condition t1CanRun = lock.newCondition(); final Condition t2CanRun = lock.newCondition(); Thread t1 = new Thread(new Runnable() { @Override public void run () { while(n < LIMIT) { lock.lock(); try { t1CanRun.await(); if (n < LIMIT) { n++; System.out.println(Thread.currentThread().getName() + ">" + n); } t2CanRun.signal(); }catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { while(n < LIMIT) { lock.lock(); try { t2CanRun.await(); if(n < LIMIT) { n++; System.out.println(Thread.currentThread().getName() + ">" + n); } t1CanRun.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }, "t2"); t1.start(); t2.start(); lock.lock(); t1CanRun.signal(); lock.unlock(); } public static void main(String[] args) { TwoThreads instance = new TwoThreads(); instance.runWithReentrantLock(); } }

Distribute Numbers So That Each Bucket Is Relatively Even
I'm working on some aspect of my game involving a depot. I'm trying to write a Resupply(stock) method so that it will resupply this depot object so that each resource in the depot is as evenly distributed as possible.
The depot has a finite maximum capacity (meaning it should not be possible to overstock a depot beyond its capacity). The depot defines a finite set of resources, that have a quantity (the number of items), as well as a multiplier (ie. You can have 4 units of Wood, but because of their large size they have a multiplier of 2, making the 4 units take up 8 units of space overall)
Take this example of a depot:
Depot A has a maximum capacity of 100, and it's current capacity is 50 (so 50% full)
There are 4 types of resources in this depot
A: 4 Units, Multiplier of 4  (4 * 4) / 100 = 16% B: 3 Units, Multiplier of 3  (3 * 3) / 100 = 9% C: 15 Units, Multiplier of 1  (15 * 1) / 100 = 15% D: 5 Units, Multiplier of 2  (5 * 2) / 100 = 10%
Now say I wish to restock this depot by giving it 25 new units (these units are magical and for gameplay purposes can allocate themselves to any resource bucket).
How would I best distribute these 25 points so that the allocation of resources A,B,C,D are more or less equal to each other?
Lets say for a first pass we add 2 Units to B, and 3 Units to D:
B: Add 2 Units  (3 + 2) * 3  15 / 100 = 0.15 D: Add 3 Units  (5 + 3) * 2  16 / 100 = 0.16
After giving 5 units away, A,B,C,D share almost the same amount of storage in the depot. (16%,15%,15%,16%)
How would I achieve this:
 With n number of resources defined in a depot?
 With any m maximum capacity?
 With any n current capacity?
 Never adding more units than the Maximum Capacity? (extra units are discarded)

What search algorithm is used by Java to search the String pool for already present Strings for String interning?
I have already read the following posts:
Neither of them mentions the search algorithm that is used by the JVM to search for String literals that have previously been created and exist in the socalled "String pool."

Sum combinations
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is:
[ [7], [2, 2, 3] ]
I deal with a problem on leetcode with golang, I got a problem, the correct result should be
[[1 1 1 1][1 1 2] [2 2]]
, but output not contains [1 1 1 1], i do not konw why, help me, plz!var combination [][]int func combinationSum(candidates []int, target int) [][]int { result := [][]int{} combination = [][]int{} backtrackingSum(candidates, []int{}, target) fmt.Printf("%v\n", combination) // unique item for _, sub := range combination { length := len(sub) if length == 1 { result = append(result, sub) } else { flag := true for i := 1; i < length; i ++ { if sub[i  1] > sub[i] { flag = false break } } if flag { result = append(result, sub) } } } return result } func backtrackingSum(candidates, solution []int, target int) { for _, candidate := range candidates { if (candidate < target) { solution = append(solution, candidate) // minus the number added backtrackingSum(candidates, solution, target  candidate) // backtracking solution = solution[:len(solution)  1] } else { fmt.Printf("%v %d\n", solution, candidate) if (candidate == target) { solution = append(solution, candidate) fmt.Printf("===%v %v\n", solution, combination) combination = append(combination, solution) fmt.Printf("%v\n", combination) } break } } } func TestCombinationSum(t *testing.T) { fmt.Printf("%v\n", combinationSum([]int{1, 2}, 4)) } console output: [1 1 1] 1 ===[1 1 1 1] [] [[1 1 1 1]] [1 1] 2 ===[1 1 2] [[1 1 2 1]] why here change to [1 1 2 1], but [1 1 1 1]? [[1 1 2 1] [1 1 2]] [1 2] 1 ===[1 2 1] [[1 1 2 1] [1 1 2]] [[1 1 2 1] [1 1 2] [1 2 1]] [2 1] 1 ===[2 1 1] [[1 1 2 1] [1 1 2] [1 2 1]] [[1 1 2 1] [1 1 2] [1 2 1] [2 1 1]] [2] 2 ===[2 2] [[1 1 2 1] [1 1 2] [1 2 1] [2 1 1]] [[1 1 2 1] [1 1 2] [1 2 1] [2 1 1] [2 2]] [[1 1 2 1] [1 1 2] [1 2 1] [2 1 1] [2 2]] [[1 1 2] [2 2]]

Python  Tricky combination
I am looking for a way to combine one element of each list below at a time, with the subsequent iteration being only able to grab among not taken elements yet.
For instance:
I have three lists. These lists would always be composed of two elements.
lst_1 = ['AB','CD'] lst_2 = [10,10] lst_3 = [30,60]
I would like to iterate two times. The first time, it selects
out = [(['AB',10,30],['CD',10,60])]
meaning two combinations of one element of each list, element that once selected can't be selected again. Please note that when I say "element that once selected can't be selected again", it is based on it's position in the list. For instance, lst_2 as twice 10. However, I select them twice because I am not looking at the value but at its position.
Second iteration:
out = (['AB',10,60],['CD',10,30])]
meaning two combination of one element of each list, combination already selected previously not being able to be selected: 'AB' for instance, could only be combined with 10 (lst_2) and 60 (lst_3), given that on the first iteration it took 30 as it's combination with the third list.
Thus far, I was able to tackle the first part (the first iteration):
test = [lst_1,lst_2,lst_3] unzipped = list(zip(*test))

plain javascript  function to get set of pairs from two arrays
given two arrays (of unknown size) like so:
var first = ['A1','A2','A3']; var second= ['B1','B2'];
I want to get set of all possible pairs from those arrays. In above example proper result should look like this:
var result = [['A1B1','A2B2'], ['A1B1','A3B2'],['A1B2','A2B1'],['A1B2','A3B1'],['A2B1','A3B2'],['A2B2','A3B1']];
I tried to come up with solution on my own, but I am stuck in increasingly bigger numer of nested loops...
EDIT:
Sorry, perhaps I wasn't that clear when forming my question. Maybe it would be easier on an example  let's assume that first array contains names of truck drivers, and second array contains cities. Each driver can only drive to one city, and each city can only be visited by single driver.
In this scenario expected output of the function would be a complete list of possible combinations (driver + city). Unknown lengths of input arrays obviously means that there may be drivers that won't drive anywhere, and there might be cities which won't get visited by any driver.
I hope now my question is more clear now.
EDIT2:
I don't think this is a duplicate of Finding all possible value combinations between two arrays since accepted answer in that question works only (if I understand it correctly) for second array of length 2.

How to become a software engineer that every big company is looking for?
I am a student of bachelor of science and technology, I have hit many walls, I did MEAN Stack programming for an year as well as Machine learning and deep learning, along with my B.tech studies. Now I am in the 6th semester of my college and have realised that companies require people who know everything about how a computer works as well as programming logic... So I have started brushing up my Algorithms and data structure. Can you help me tell some sources you did study from?

get checkbox state from dynamic element
I'm using the YouTube API to populate a list of cards to my app using an each function. These cards are placed into a variable, then appended to a playlist container.
Within the individual cards is a switch to "favorite" a video. The switch, along with rest of the card is populated dynamically, so I'm trying to use the "on" "change", instead of ".change" "function". From what I've ready the on method is what you use to manipulate dynamic elements.
The challenge I'm running into is that I cannot seem to get the correct state of the switch(checkbox), and I'm always returning the first if statement no matter what I'm doing. Can anyone spot what I'm doing wrong here? The plan is to push to firebase if a user clicks to "favorite" a video, but I cannot get this function working. Thanks in advance! :D
$(document).on("change", ".switch", function () { if (this.checked) { console.log("Checked"); } else { console.log("NOT Checked"); } });

Knapsack Algorithm Code
I am trying to code the algorithm for the knapsack problem in C++. I can't get this to work. I am getting max sum equals 0 for any input. I think the problem relies in the nested forloop. Can someone point out what went wrong and how to fix the code ?. I would like to know also what you think about my implementation. Thanks for the help.
#include <iostream> #include <vector> #include <set> #include <utility> using namespace std; using knapsack_pair = pair<int,int>; // pair<value,weight> using matrix_value_type = pair<int, set<knapsack_pair>>; // pair<max, set of elements> matrix_value_type max(matrix_value_type first_value, matrix_value_type second_value){ if(first_value.first >= second_value.first) return first_value; else return second_value; } int main(){ int number_of_values; int knapsack_size; cout << "How many values are you going to enter?" << endl; cin >> number_of_values; cout << "what's the size of the knapsack?" << endl; cin >> knapsack_size; int counter = 0; vector<knapsack_pair> knapsack_vector; while(counter < number_of_values){ knapsack_pair new_pair; cout << "insert the value of the element" << endl; cin >> new_pair.first; cout << "insert the weight of the element" << endl; cin >> new_pair.second; knapsack_vector.push_back(new_pair); ++counter; } matrix_value_type matrix[number_of_values + 1][knapsack_size + 1]; for(int i = 0; i < knapsack_size + 1; ++i){ set<knapsack_pair> empty_set; matrix_value_type value(0,empty_set); matrix[0][i] = value; } for(int x = 1; x < number_of_values + 1; ++x){ knapsack_pair current_pair = knapsack_vector.at(x1); for(int y = 0; y < knapsack_size + 1; ++y){ matrix_value_type first_value = matrix[x1][y]; matrix_value_type second_value; int weight_s_pair = y  current_pair.second; if(weight_s_pair >= 0){ second_value = matrix[x1][weight_s_pair]; second_value.first = second_value.first + current_pair.first; second_value.second.insert(current_pair); } else second_value.first = 999; matrix[x][y] = max(first_value,second_value); } } matrix_value_type result = matrix[number_of_values][knapsack_size]; cout << "the max value is: " << result.first << endl; cout << "the elements in the knapsack are: " << endl; for(auto& it : result.second) cout << "element of value: " << it.first << " and weight: " << it.second; }

Recursive Knapsack in R
I wrote the following code in
R
for recursive solution of knapsack problem, but the output is NULL. Please let me know where I am making errors.k.capacity< 8 k.value< c(15,10,9,5) k.weight< c(1,5,3,4) k.sol< for (i in 1:4) { if(k.weight[i]>k.capacity) return(k.weight[i1]) else(max(k.value[i]+k.value[i1]&&(k.capacityk.weight[i1]) k.value[i1] && k.weight[i])) }

Complexity Analysis Unbounded Knapsacklike (profit)
I found myself unable to reach a runtime BigO boundary expression for the following python code:
def profit3(values_lst, size): n = len(values_lst) return profit_rec(values_lst, n, size) def profit_rec(values_lst, i, size): if size==0 or i==0: return 0 if size==1: return values_lst[0] else: return max(values_lst[i1]+profit_rec(values_lst,min(i, sizei),sizei), profit_rec(values_lst, i1, size))
Code is intended to give a land owner (land size) the maximum value he can get on his property if he divides the property into smaller areas where values_lst contains the value of each size (index 0 for size 1, index 1 for size 2, etc.)
This is quite similar to the unbounded knapsack problem as size is akin to weight, and we can use the same size again and again within our problem. However, I did not manage to find a good source that I will understand fully why the complexity of the unbounded knapsack problem is
O(nW)
, which in the profit case, would translate toO(n^2)
? .. and my runtime analysis shows thatO(n^2)
is too small for this solution, albeit,profit3()
does not apply memoization, which might be the crux of the matter. Regardless, I'd like to be able to find the BigOh of the current problem and would appreciate some help.