Binomial Min Heap delete issue - binomial-heap

Got this problem on a recent CS class quiz that I got wrong. These were the choices:
3,4
10,13
10, 9
10
I put 10 and am pretty sure I am right. Can someone explain why I am not?

It's been a long time, but here's how it should work:
Remove 1 creating new heaps 2->10 and 9 (orders 1 and 0).
Merge these with the rest of the heap.
2->10 stays as-is. There's no other order 1 heap (for now).
Merge 9 and 13 into 9->13.
Now merge 9->13 and 2->10 to get a new order 2 heap.
2->10
-> 9->13
There's no other order 2 heap, so we're done.
So the children of 2 are 9,10.

Related

Modulo alternative Lua

I don't have much coding experience so I don't really know of an efficient alternative to modulo, the issue I have is that I want to have the same funcionality but witouth it ever returning zero if that makes sense.
So I have an arbritary value % 8 and I want my results to go (1,2,3,4,5,6,7,8,1,2,3,etc)
any help or push in the right direction would be appreciated.
I assume you're trying to make indices from 1 to 8 loop. For zero-based offsets from 0 to 7 this would be trivial by using i % 8; consider simply making your table zero-based.
For one-based indices, the simplest way to go is to first subtract 1 to make it zero-based, then apply the modulo to wrap around, then add 1 to make it one-based again: ((i - 1) % 8) + 1.
So I have an arbritary value % 8 and I want my results to go
(1,2,3,4,5,6,7,8,1,2,3,etc)
local result = value % 8 + 1
This is a simple maths problem. If one arrithmetic operator doesn't give you the desired result, use or add others to your formula.

How to break from a loop in Maxima

I am new to Maxima. I am trying to write a loop in that I am checking if some condition met then exit from the loop.
cp:for i:1 step 1 thru 10 do
block(if(i>6) then break()
else
print(i,"is less than 6"));
I want output:
1 is less than 6
2 is less than 6
3 is less than 6
4 is less than 6
5 is less than 6
6 is less than 6
But when I am running the above code :
after printing 6 is less than 6, it is prompting
Entering a Maxima break point. Type 'exit;' to resume.
and after typing exit; it will again show the above msg
I want the code will come out completely from that loop rather than asking to type exit;
Thank you in advance..
Try return(i) instead of break(). Also, return only returns from the block which encloses it, so you need to remove the block(...) in your example (it's unneeded anyway). I think this works:
cp: for i:1 step 1 thru 10
do if(i>6) then return(i) else print(i,"is less than 6");

Stack: The terminlogy and example

For this simple problem, I need to find the value(s) of stack1 and in order, if any. When it comes to the stack, the principle is LIFO (last in, first out) or FILO (first in, last out). And the reason stacks are used is to reverse the data, and displaying it in reverse order.
Stack<Integer> stack1 = new Stack<Integer>();
stack1.push (2);
stack1.push(5);
stack1.push (stack1.pop() - stack1.pop());
stack1.push(8);
The question above made me think, if we were to use the principle, should the answer be this: 8, 3, 5, 2.
8 being the last value being the start, then the next value being 3, from taking 5 and 2 (the "pop" being the deletion at the "head"). Then the next two values being 5 and 2. Would that be the right answer, or did I got the incorrect answer?
The Stack is a LIFO (last in first out). Look at it from the point of view of the first element you put in. You should also check this out what is the basic difference between stack and queue?.
As for the example, the answer is 8 and 3 only because when you calculated the 3 as stack.pop() - stack.pop() you deleted the 5 and the 2 from the stack, so they won´t be there anymore.
Stack stack1 = new Stack(); []
stack1.push (2); [2]
stack1.push(5); [2,5]
stack1.push (stack1.pop() [2] - stack1.pop() [] ); [3]
stack1.push(8); [3,8]

Greedy algorithm to finish a task with time constraint

This is a question from my midterm today and I wonder how to solve this. All i know is to prove the greedy algorithm using induction.
Question:
You are working on a programming project. There are n Java classes C1, C2, ..., Cn (the bossy architect says so). The architect also says that these classes have to be implemented in order (you are not allowed to implement C2 before you have completed C1 and so on).
Each of the Java classes takes at most 8 hours to implement. You work exactly 8 hours a day, and you should not leave a Java class unfinished at the end of the day.
To complete the project as soon as possible, a strategy is to implement as many classes as you can everyday. Prove that this greedy strategy is indeed the optimal one.
(Hint: let ti be the total number of classes completed in the first i days using the above strategy. The strategy always stays ahead if ti is no less than the total number of classes completed in the first i days using any other strategy)
This problem is similar to the classic task scheduling case where the waiting time in the system must be minimized.
Let C1, C2, ..., Cn your projected classes and c[1], c[2], ..., c[n] their required implementation time. Let's suppose you implement C1, C2, ... Cn in this order. Therefore, the total time (waiting + implementation) for each class Ck will be:
c[1] + c[2] + ... + c[k]
Therefore, we have the total time:
T = n·c[1] + (n – 1)·c[2] + ... + 2*c*[n – 1] + c[n] = sum(k = 1 to n) of (n – k + 1)·c[k]
(Sorry about the presentation — superscripts, subscripts, and math equations aren't supported...)
Let's suppose the implementation times in our permutation are not sorted by ascending order. We can therefore find two integers a and b such that a < b with c[a] > c[b]. If we switch them in the computation of T, we have:
T' = (n – a + 1)·c[b] + (n – b + 1)·c[a] + sum(k = 1 to n except a, b) of (n – k + 1)·c[k]
We finally compute T – T':
T – T' = (n – a + 1)(c[a] – c[b]) + (n – b + 1)(c[b] – c[a]) = (b – a)(c[a] – c[b])
Following our initial hypothesis (a < b and c[a] > c[b]), we have b – a > 0 and c[a] – c[b] > 0 as well, hence T – T' > 0.
This proves that we decrease the total waiting time by switching any pair of tasks so that the shorter one is done first.
Your problem statement is the same, except that before starting implementing a new class, you have to check whether you should start it now (if there is enough time left on the present day) or tomorrow. But the principle proven here holds when it comes to minimizing the total "waiting" time.
This is not a programming question for SO. The problem is not asking for a coding solution, rather its a proof that greedy is optimal. Which can be done with a proof by contradiction (no doubt taught in the class before the midterm).
What you want to do is to calculate the total time taken by greedy (there's only one solution) and disprove that any swaps in day would lead to a better solution. You probably also have to add something that mentions how swapping will allow u to permute the order to the optimal solution, if it exists.
I was going to write some formulae, but i realize Jeff Morin already has the equations, just going in the opposite direction. I think starting from the greedy solution might be easier to explain, since 'in order' is pretty much defined by the problem and you can only shift the work +- which day its done on.
The problem statement is incomplete. There is no indication that any class will take less than 8 hours. Since you can't leave any class unfinished, then you must start each class at the start of the day to be sure to have at least 8 hours to work on it. So if C2 really takes 3 hours and C3 really takes 5 hours, then a greedy algorithm would allow both classes to be done the same day. But after C2 takes 3 hours, you have to wait to day 3 to start C3 to be sure that you have enough time to finish since you don't know how long C3 will take.
So the restrictions really end up dictating that the effort will take n days, 1 day per class. So the implementation algorithm is strictly sequential, not greedy.
Edit Restrictions stated in problem.
(1) There are n Java classes C1, C2, ..., Cn
(2) these classes have to be implemented in order (you are not allowed to implement C2 before you have completed C1 and so on).
(3) Each of the Java classes takes at most 8 hours to implement
But there is no estimate for any class taking less than 8 hours.
(4) You work exactly 8 hours a day
(5) You should not leave a Java class unfinished at the end of the day.
The gist of this (3,4,& 5) is let's assume that I work on class 1 for 5 minutes. I now have 7 hours 55 minutes left. Can I start on Class 2? No because it might take up to 8 hours and I must finish before the end of my 8-hour day. So I must wait to day 2 to start class 2 and so on. Thus the implementation is strictly sequential and will take n days to complete, 1 day per class.
In order to use the Greedy algorithm you'd need additional information.
(6) You also know that each class has a known number of hours needed to code the class - h1, h2, h3, ..., hn. So class 1 takes h1 hours, class 2 takes h2 hours and so on. (From item 3 no class takes more than 8 hours)

Generating means of a variable using dummy variables & foreach in Stata

My dataset includes TWO main variables X and Y.
Variable X represents distinct codes (e.g. 001X01, 001X02, etc) for multiple computer items with different brands.
Variable Y represents the tax charged for each code of variable X (e.g. 15 = 15% for 001X01) at a store.
I've created categories for these computer items using dummy variables (e.g. HD dummy variable for Hard-Drives, takes value of 1 when variable X represents a HD, etc). I have a list of over 40 variables (two of them representing X and Y, and the rest is a bunch of dummy variables for the different categories I've created for computer items).
I would like to display the averages of all these categories using a loop in Stata, but I'm not sure how to do this.
For example the code:
mean Y if HD == 1
Mean estimation Number of obs = 5
--------------------------------------------------------------
| Mean Std. Err. [95% Conf. Interval]
-------------+------------------------------------------------
Tax | 7.1 2.537716 1.154172 15.24583
gives me the mean Tax for the category representing Hard Drives. How can I use a loop in Stata to automatically display all the mean Taxes charged for each category? I would do it by hand without a problem, but I want to repeat this process for multiple years, so I would like to use a loop for each year in order to come up with this output.
My goal is to create a separate Excel file with each of the computer categories I've created (38 total) and the average tax for each category by year.
Why bother with the loop and creating the indicator variables? If I understand correctly, your initial dataset allows the use of a simple collapse:
clear all
set more off
input ///
code tax str10 categ
1 0.15 "hd"
2 0.25 "pend"
3 0.23 "mouse"
4 0.29 "pend"
5 0.16 "pend"
6 0.50 "hd"
7 0.54 "monitor"
8 0.22 "monitor"
9 0.21 "mouse"
10 0.76 "mouse"
end
list
collapse (mean) tax, by(categ)
list
To take to Excel you can try export excel or put excel.
Run help collapse and help export for details.
Edit
Because you insist, below is an example that gives the same result using loops.
I assume the same data input as before. Some testing using this example database
with expand 1000000, shows that speed is virtually the same. But almost surely,
you (including your future you) and your readers will prefer collapse.
It is much clearer, cleaner and concise. It is even prettier.
levelsof categ, local(parts)
gen mtax = .
quietly {
foreach part of local parts {
summarize tax if categ == "`part'", meanonly
replace mtax = r(mean) if categ == "`part'"
}
}
bysort categ: keep if _n == 1
keep categ mtax
Stata has features that make it quite different from other languages. Once you
start getting a hold of it, you will find that many things done with loops elsewhere,
can be made loop-less in Stata. In many cases, the latter style will be preferred.
See corresponding help files using help <command> and if you are not familiarized with saved results (e.g. r(mean)), type help return.
A supplement to Roberto's excellent answer: After collapse, you will need a loop to export the results to excel.
levelsof categ, local(levels)
foreach x of local levels {
export excel `x', replace
}
I prefer to use numerical codes for variables such as your category variable. I then assign them value labels. Here's a version of Roberto's code which does this and which, for closer correspondence to your problem, adds a "year" variable
input code tax categ year
1 0.15 1 1999
2 0.25 2 2000
3 0.23 3 2013
4 0.29 1 2010
5 0.16 2 2000
6 0.50 1 2011
7 0.54 4 2000
8 0.22 4 2003
9 0.21 3 2004
10 0.76 3 2005
end
#delim ;
label define catl
1 hd
2 pend
3 mouse
4 monitor
;
#delim cr
label values categ catl
collapse (mean) tax, by(categ year)
levelsof categ, local(levels)
foreach x of local levels {
export excel `:label (categ) `x'', replace
}
The #delim ; command makes it possible to easily list each code on a separate line. The"label" function in the export statement is an extended macro function to insert a value label into the file name.

Resources