Minimum Set to satisfies the condition & formulae - Algorithm

I need a solution for this problem. Please help..
Problem:</
Input:_
Let N = 100
{x y}
{1 2} - A
{2 3} - B
{1 2} - C
{1 5} - D
Condition:_
I can pick any set from the above, like {A, B} or {A, A, A, A....} or {A, B, D} or {A, A, B, B, C, C, C, ...} etc...
Formulae:_
example:
for {A, B}, the formulae is --> (Ax + Bx)^2 + (Ay + By)^2 = N^2
for {A, B, D}, the formulae is --> (Ax + Bx + Dx)^2 + (Ay + By + Dy)^2 = N^2
i.e) (sum of all selected element's x value) ^ 2 + (sum of all selected element's y value) ^ 2 = N ^ 2
Output: _
The minimal number of elements that can be used to achieve the condition.
example, if both {A, B} & {A, C, D} satisfies the formulae then my solution is {A, B} which has minimal elements in the set. so the output will be 2. if no solution, then return -1.
Hope I have explained it clearly. Please help...

First find the Pythagorean triples corresponding to a*a + b*b = N*N. This will give integer values of a and b which your x and y values should total to. This simplifies the next stage, as finding a set of values k1*x1+k2*x2+... + kn*xn = a reduces the search space somewhat - your last term will always be ( a - (k1*x1..kn-1*xn-1) ) / xn.
Order your values so xi > xi+1. This means you can stop easily when xi == 0, and it's typically bit faster to try removing the biggest values first.
You can also use dynamic programming to avoid some repeated calculations, but even without it's fairly fast, even for 20 or so different vectors in the basis.
    static class FindMinimimSet implements TripleProcessor {
        int bestTotal = Integer.MAX_VALUE;
        final int[][] basis;
        final int[] counts;
        final HashMap<Long,Integer> memo = new HashMap<Long,Integer>();
        // basis should be sorted by x then y with maximum values first,
        // eg { {4,3}, {4,2}, {0,4}, {0,2} }
        FindMinimimSet ( int[][] basis ) {
            this.basis = basis;
            this.counts = new int[basis.length];
        public void triple ( int a, int b, int c ) {
            bestTotal = findMinimumSet( a, b, bestTotal );
            if ( a != b )
                bestTotal = findMinimumSet( b, a, bestTotal );
        int findMinimumSet ( int a, int b, int bestTotal ) {
            return findMinimumSet ( a, b, 0, new int[basis.length], 0, bestTotal );
        int findMinimumSet ( int a, int b, int i, int[] counts, int total, int bestTotal ) {
            long key = (a * 104729L + b) * 104729L + i;
            Integer val = memo.get(key);
            if (val == null) {
                // TODO: record actual counts too
                val = reallyFindMinimumSet(a,b,i,counts,total,bestTotal);
                memo.put(key,val);
            return val;
        int reallyFindMinimumSet ( int a, int b, int i, int[] counts, int total, int bestTotal ) {
            if ( ( a == 0 ) && ( b == 0 ) ) {
                // todo - save the counts somewhere rather than just outputting them
                System.out.println( total + " -> " + Arrays.toString( counts ) );
                return total;
            if ( i >= basis.length )
                return Integer.MAX_VALUE / 2;
            int[] vector = basis;
if ( i < basis.length - 1 ) {
final int maxCount = Math.min ( bestTotal - total, Math.min ( ( vector[0] > 0 ) ? a / vector[0] : b, ( vector[1] > 0 ) ? ( b / vector[1] ) : a ) );
// if the next value of x is zero, and this value isn't, count must be exact
if ( ( vector[0] != 0 ) && ( basis[i+1][0] == 0 ) ) {
if ( vector[0] * maxCount != a )
return bestTotal;
} else {               
for ( int count = maxCount; count >= 0; --count ) {
counts[i] = count;
bestTotal = findMinimumSet( a - vector[0] * count, b - vector[1] * count, i+1, counts, total + count, bestTotal );
return bestTotal;
// only check the max count for last in vector/last with non-zero x
final int count = Math.min( ( vector[0] > 0 ) ? a / vector[0] : b, ( vector[1] > 0 ) ? ( b / vector[1] ) : a );
if ( total + count < bestTotal ) {
counts[i] = count;
bestTotal = findMinimumSet( a - vector[0] * count, b - vector[1] * count, i+1, counts, total + count, bestTotal );
return bestTotal;
The code to find Pythagorean triples, given the longest side:public interface TripleProcessor {
void triple ( int a, int b, int c ) ;
public static void findTriples ( int c, TripleProcessor out ) {
final int c2 = c * c;
final HashMap<Integer,Integer> squares = new HashMap<Integer,Integer>(c2);
for ( int i = 1; i < c; ++i )
squares.put(i*i, i);
for ( int a = 1; a < c; ++a ) {
final Integer b = squares.get(c2 - a*a);
if ( b != null )
if ( a <= b )
out.triple(a,b,c);
else
break;

Similar Messages

  • How to set the conditions for item deletion approval workflow?

    Hi,
    I have created approval workflow for item modifications ie, when user try to modify an item, it will send a mail to Project Manager. For that I set the conditions in Change the behavior of the overall task: 1. When the task process starts 2 . When the task
     process completes .
    Change the behavior of the single task: 1.when a task is Pending.
    [I followed this https://www.nothingbutsharepoint.com/sites/eusp/Pages/5-Steps-to-Enhance-SharePoint-2010-Approval-Workflow.aspx ]
    My Requirement is that I want to set this same workflow for the scenario: when the user deletes an item it will send a mail (intimation mail for item deletion) to Project Manager. here i dont want to send modification mails when user deletes an item.
    When user modifies an item: 1. intimation mail, 2. Approve/Reject mail 3. intimation for approval / rejection mail.
    When user deletes an item: 1. intimation mail.
    How can we set it in one approval workflow?? where i have to set the condition for sending either item modification mails or deletion mail.
    Thanks,
    Praveen ji

    Hi,
    According to your post, my understanding is that you wanted to start approval workflow when item deleted.
    You should first make some changes to trigger the workflow when you delete the item.
    You can use the Event Receiver to achieve it.
    In order to trigger workflow on item delete you need to create event receivers and from event receiver call the workflow already attached with list.
    http://ravendra.wordpress.com/sharepoint-workflow-on-list-item-delete/
    You can also create custom action to start the workflow, you can refer to the following article, then modify the workflow as your need.
    http://blogs.sharepoint911.com/blogs/jennifer/Lists/Posts/Post.aspx?ID=50
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • 'Use minimum version required by the Flex SDK' setting question

    Hi,
    Can someone explain why after downloading the latest stable Hero SDK (build 19786), which only has fp10.2 support in the framwork/libs/player directory, would the 'Use minimum version required by the Flex SDK' build property still tell Flash Builder to build for fp10.1?
    In my flex-config.xml file from this new SDK, I see the target-player attribute is set to 10.2. Is there a bug in burrito that would fail for that value to be used?

    No. That should work. Builder also reads the minimum value from flex-config.xml.
    Just to check - you added this as a new SDK in Preferences -> Flash Builder -> Installed Flex SDKs and either made that the default SDK or changed the project to use the new SDK, right?

  • How to set colors in cells depending the conditions  in alvtree

    Hi All,
    Could you please provide me idea or sample program how to set colors in cells depending the conditions  in alvtree.
    Thanks,
    Suresh

    When running vim in a terminal, it will use whatever colour scheme is defined by the terminal.  You should have a look at this thread:
    http://bbs.archlinux.org/viewtopic.php?id=51818
    Also, check the wiki article on Xdefaults.

  • What's the minimum setting for WL as a proxy server

              What's the minimum setting of weblogic.properties for WL as a proxy server?
              

    Hi Michael,
    Recommended setting is the default setting which is 25 .dot.
    If your situation is abnormal and you see message delivery throttling state to “4” when the following performance counters are high or if you expect any of you integration
    process could have impact on following counters, then you can consider the suggestion by Microsoft. Don’t change the default setting.
    High process memory
    Process memory usage (MB)
    Process memory usage threshold (MB)
    You can see these counters under “BizTalk:MessageAgent”
    You can gauge these performance counter and its maximum values if have done any regression/performance testing in your test servers. If you have seen these counters having
    high values and causing throttling, then you can update the Process memory usage.
    Or unexpectedly you’re process high throughput messages in production which is causing these counters to go high and cause throttling, then up can update the Process memory
    usage.
    The above two cases where I know my expected process usage (by doing performance testing) or suddenly my production server processing has gone high due to unexpected business
    hike (or any reasons) which caused throttling, then do changes to default throttling setting.
    Just changing the default setting without actual reason could have adverse effect where you end up allocating 
    more processing capacities but the actual message processing message usage ever is low means you end up investing in underutilised resources.
    Regards,
    M.R.Ashwin Prabhu
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Hello, I trying to create a program that would run a household furnace. I can't find a way to set timers for the ignitor,flame sensor and blowers. Any thoughts.

    Hello, I'm trying to create a program that would run a household furnace. I can't find a way to set timers foe the ignitor,flame sensor and blowers. Any thoughts would be greatly appreciated. Thanks, primetime

    In the detailed help for the event structure there is a link to caveats and recommendations for using event structures.  It is a good starting point.
    It is courteous to let the Forum know when your questions are related to a school assignment or homework.  We are glad to help you learn LabVIEW, but do not do your homework for you.
    You have learned the major disadvantage of the sequence structure: It must run to completion before anything else can happen.
    If you are building a state machine (typically a while loop with shift registers enclosing a case structure with one case per state) and having trouble with timing, then think about your requirements. Apparently you have some time delays, but under certain conditions you must terminate a delay/wait and do something else.  One way of doing this is to have a Wait state.  The wait state has a short delay, determined by the minimum time you can delay responding to a changed condition, and a check to see if the required elapsed time has occurred.  If the time has not elapsed, the next state is the Wait state again.  The state machine can repeat any state as often as necessary.  So a 15 second delay could be implemented by going to a Wait state with a one second wait 15 times. Any error or new command will see a response in no more than one second.
    Lynn

  • How to grey out or deactivate the Conditions tab in VA01 and VA02

    Hi gurus,
    Is there a way I can grey out or deactivate the Conditions tab in VA01 or VA02?  Our objective is to attach the pricing conditons to the customer level and that no sales encoder can edit prices during encoding using t-codes VA01 and VA02?
    I also tried to solve my problem through authorization object of the user V_KONH_VKS - set to 3 (Display) but still the user was able to make revisions to the Conditions tab if he wants to.  This is an internal control issue  for our company.
    Thanks for the immediate response. 
    Frances

    Hello Francis,
    In the definition of condition types in SPRO ( T.code V/06) you can define whether a particular condition type ( example PR00) can be processed manually by the user. IF you select the option " No Manual entries" the system does not allow the users to change the condition value determined from the condition records ( Maintained in VK11).
    ALternately, if the business requirement is that of allowing a particular condition type ( example PR00) to be processed manually by the user in certain business scenarios and in others the value should not be editable then you can use the user exit in MV45AFZB " USEREXIT_SAVE_DOCUMENT". In this you can write the required logic with the help of a technical consultant.
    Hope this helps
    Warm Regards
    Prashant Joshi.

  • How to hide the Condition types in item condition screen in Sales Order ?

    Hi Experts,
    We got new requirement from the Client. Pricing Condition types  are ZZBG, ZPBG, ZPBA, ZFSG, ZBDG and ZBHG part in Pricing Procedure. These condition types have Condition records. These need to be hidden in Item conditions screen in Sales Order but other status of the conditions remain unchanged. Pleas provide me the solution earliest  How this we can achieve in a best way.
    Best Regards,
    Srikith

    Hi Srikanth,
    You can achieve this using CONDITION EXCLUSION.
    Maintain Condition exclusion for first condition type its Exclude the condition types which are below to that.
    You must set a condition exclusion indicator for the price. You can do this in two ways:
    If you want to set the condition exclusion indicator a follows then you specify it:
    1..for all condition records of a condition type (e.g. with condition type PR00) when defining a condition type in SD Customizing
    2.for an individual condition record (e.g. only for material 4711) in the detail screen of a condition record (in the Condition exclusion field)
    Hope this will helps you
    Dasaradha

  • IPC: How to read the Condition Rate(KBETR) in Java checkRequirement method.

    Hi Experts,
    As part of an IPC development, we need to read the Condition Type Rate (KBETR) in a Requirement Formula. The condition rate is the rate for the current record of the pricing procedure, e.g. Condition Type ZAB1.
    I can successfully read the condition rate in a Value formula using this piece of code:
    public BigDecimal overwriteConditionValue(IPricingItemUserExit pricingItem,IPricingConditionUserExit pricingCondition) {
                      BigDecimal ZConditionRate = pricingCondition.getConditionRate().getValue();
    In a Value Formula "IPricingConditionUserExit pricingCondition" is a input parameter of the overwriteConditionValue() method. However in a Requirement formula the standard method checkRequirement(IConditionFindingManagerUserExit item, IStep step, IAccess access) does not have any parameter which can give me the rate.
    I wrote the following logic in the requirement class, but line 2 is not executed.
    1. public boolean checkRequirement(IConditionFindingManagerUserExit item, IStep step, IAccess access) {
         2.  IPricingConditionUserExit pricingHeader = (IPricingConditionUserExit) item;
         3.  BigDecimal ZConditionRate = pricingHeader.getConditionRate().getValue();
    Please suggest how we can retrieve the condition rate in a requirement formula class using teh standard methods & classes.

    Hi,
    I have to set the condition rate as percentage in one of my codition value formula routine which i am developing based on java.
    I have overwritten  the method overwriteConditionValue() in my pricing routine which is 927. My logic is below.
    When I open my quotation using crmd_order, condition rate is not being displayed with % for unit condition rate coulmn in my pricing conditions.
    If I try to change my quotation for ex: Agrred price: xworke, then 927 formula is called and condition rate is displayed as %.
    So condition rate value is displayed perfectly , but when my quotation is in display mode condition rate value is coming as USA, but it should be % irrespective of my quotation is in display mode or change mode. I have attached the two screen shots for quotation display mode and change mode.
    Can some body throw insight what is wrong in my pricing routine logic in setting % condition rate rather than USD for the Condition rate value.
    public BigDecimal overwriteConditionValue(IPricingItemUserExit pricingItem,
      IPricingConditionUserExit pricingCondition) {
      BigDecimal condValue = null;
      BigDecimal discountValue = null;
      try{ 
        BigDecimal xworkg = pricingItem.getSubtotal(PricingCustomizingConstants.ConditionSubtotal.SUBTOTAL_G).getValue();
        userexitlogger.writeLogDebug(" 927 formula, Date=["+new Date()+"] , xworkg=["+xworkg+"]");
        BigDecimal xworke = pricingItem.getSubtotal(PricingCustomizingConstants.ConditionSubtotal.SUBTOTAL_E).getValue();
        userexitlogger.writeLogDebug(" 927 formula, Date=["+new Date()+"],  xworke=["+xworke+"]");
        pricingCondition.setCalculationType(PricingCustomizingConstants.CalculationType.PERCENTAGE); 
        if (xworkg.compareTo(PricingTransactiondataConstants.ZERO) != 0) {   
        condValue =  xworkg.subtract(xworke);
        pricingCondition.setConditionValue(condValue); 
        // Calculate percentage with 3-decimal-precision (as does ABAP-Version by multiplying with 100.000 instead of 100)
        pricingCondition.setConditionRate(condValue.multiply(PricingTransactiondataConstants.HUNDRED).divide(xworkg,
          3, BigDecimal.ROUND_HALF_UP), "%");
        pricingCondition.setPricingUnit(new BigDecimal(0), null);
        else {
        pricingCondition.setConditionRate(PricingTransactiondataConstants.ZERO, "%");
        pricingCondition.setPricingUnit(new BigDecimal(0), null);
      catch (Exception ex) {
        //pricingCondition.setInactive(PricingCustomizingConstants.InactiveFlag.INACTIVE_DUE_TO_ERROR);
        userexitlogger.writeLogError("Error Occured in 927 formula, reason code=["+ex.getMessage()+"]");
        return null;
      //return condValue;
      return null;
    Thanks
    Srikar

  • Price was not picking from the Condition type for Item Category 'P'  in PO

    Hi Experts,
    I Created one condition type based on Material and WBS which price was fixed based on this
    I used the Purchase Order having Item <b>Category ‘P’ or ‘Q’</b> Price should pick from the condition type where I mapped the WBS Element and Material.
    The Net price was not picking from the Condition type Record.  Why? What should be the Problem?
    Whether my logic is correct or not?
    <u><b>
    The Scenario:</b></u> I want to fix the Material price base on each WBS Element for a Project. For each WBS Element the Price will be various for same material.
    Please help on this.
    Thanks
    Muthukumar

    Hi,
    In standard configuration you cannot set item delivery date as a pricing data.
    Maybe you shoud look at SAP enchancement - in dedicated structures you can pass additional item data (structure KOKMP).
    IMG link:
    Materials Management -> Purchasing -> Conditions -> Define Price Determination Process -> System Enhancements
    hope it helps.
    regards,
    wojciech

  • Changing the Condition type Text in the Purchase Order

    Hi SAP,
    Hi,
    We have a requirement where by we need to change the Description of the condition type text in the Purchase order.
    The condition type is a entered at item level.
    Normally this description comes from the Condition type Definiton i.e., T685T-VTEXT.
    can any one of you suggest a User exit or a method where by we can change this text at PO.
    Has any one of you came across such situation before. if so please provide me with your inputs.
    Thanks
    Best Regards
    ShitalD
    Edited by: Shital Deshpande on Feb 21, 2010 1:07 PM

    Hi,
    I think it is a config setting..Please check with your functioal consultant regarding the same.. I won't suggest to change the standard SAP table T685T but you can keep it as last option .
    From SPRO you can follow the below path
    Sales and Distribution->Basic Functions -> Pricing > Pricing Control -> Define condition types.
    Regards,
    Nagaraj

  • How to set password in the form, request is coming from SPML with no pwd

    Hi ,
    Im using SPML request to create and modify users? I have 2 problems
    1) Does anyone know, how to customize the form to call 2 different workflow depending on the request meaning, if SPML request is ADD, then it should call Create User workflow, and SPML request is MOD then it should call Update User workflow.
    Right now, i don't know who to do it and currently it is working for create users only.
    2) Im not getting password field from SPML request, so i have to set password with value 'password' in the form. Can i do that and How?
    Appriciate any response

    Hi,
    According to your post, I know you want to add a custom field to Task form. When vale is Yes, send the email to the assigned person. When the value is No, item update and user can approve the task without the email sending out.
    Doubt you have already create an approval workflow which associated with Task list in SharePoint Designer.
    1. To add new fields to Task Form, click New button in Task Form Fields section. Name the “Send the email or not” of choose type. See the below image:
    Then, save and publish the workflow to make it effect. You can visit the following article for details:
    Updating List Item with Task Form Custom Field in SharePoint Approval 2010 Workflow
    http://blogs.msdn.com/b/kishore/archive/2012/01/15/updating-list-item-with-task-form-custom-field-in-sharepoint-approval-2010-workflow.aspx
    2. In SharePoint Designer, create another workflow which associated with Task list.
    a. Click workflows > List Workflow and choose Task list.
    b. Add the condition, if the current item: “Send the email or not” is equals to yes. Then, add the action “Send an email”.
    c. Publish the workflow.
    Thanks.
    Tracy Cai
    TechNet Community Support

  • How to set a BEx Query Condition in Design Studio (e.g. Net value GT 0)

    Hi experts,
    I have set a simple condition in my BEx Query...
    e.g. key figure "Net value" GT 0 to become only positive values in the query result.
    In the Query runtime the condition works successful, but in the Design Sudio view the defined Query condition doesn´t work.
    In my Design Studio crosstab I have tried to switch between the display setting "Conditional formating Visible" true/false, but without success.
    By the way, before I have posted this thread, I had a look at this two blogs...
    Design Studio 1.0: Create a Scorecard Using SAP BW BEx Query Exceptions
    Design Studio 1.2  - a Second Look
    Any ideas or experiences?
    Thanks and regards,
    Michael

    Hi Michael,
    I think you are mixing up two different BEx terms. Conditions are filters on key figures (show me only the results with a value bigger than 50). Exceptions do not filter the result set, but provide a formatting based on the values in the result set (if value is bigger than 50, make its cell red).
    The Conditional formatting setting in Design Studio refers to the BEx exceptions. For the BEx conditions there isn't such a setting available. You just have to activate the condition in your BEx Query and use that for your data source in Design Studio.
    If you want a workaround to enable/disable conditions from Design Studio, check this blog I wrote: HackingSAP.com - SAP Design Studio and Conditions It shows how you can use variables to adjust the conditions (and also activate) from within Design Studio.
    Cheers,
    Xavier

  • Displaying record based on the condition in Crystal report

    Hi All,
    I want to display certain records in crystal based on some condition.
    For example,
    If I am having 5 student records like,
    Name  Mark1 Mark2 Mark3 Total
    aaa      40       50       60      150
    abc      30       60       40       130
    tcr        25      25        25       75
    Now in table i have only 4 fields (STUNAME, MARK1, MARK2, MARK3).
    I have to calculate the total at runtime and if total is greater than 150, then actual record should display in report.
    For example, I can use formula to calculate total but I can calculate total only after each record prints. But i want to calculate total internally only it should display in report if condition satisfies. I dont want to keep one more field for total in crystal report.
    Please help me on this.

    If the filter is not "pushed" down to the database, then Crystal will pull all of the data into memory and then filter it there.  This is not a big deal if you only have a couple of records, but it can significantly slow down a report that is pulling in more than a few records.
    An alternative, if your report is just linking tables in the Database Expert, would be to create a SQL Expression that adds the three fields together.  Using this in the Select Expert WILL push the condition down to the database.
    If you're using a command instead of linking table, they you would add this to the Where clause of the comment.  If you're using a stored proc instead of tables or a command, you would want to do this filter in the code for the stored proc.
    -Dell
    Message was edited by: Dell Stinnett-Christy

  • Hidding the condition in reports

    Hello All,
    I have genarated a report with some binding variables, It will produce a custom form for the values to consume.
    there is a drop down box in the custom report for conditions to be set. I want to hide this drop down box for the end user.
    Or How to build the "Reports From Query Wizard" without the drop down box(which contains the condition, I will set the conditions by saving them once..) or hide in the custom report which is provided by the portal prior to genarate report.
    thanks in advance

    Greetings,
    Hi,
    I have a JSP that generates links to a Servlet, the problem is that in the M$-Explorer the url appears
    when you pass the mouse-pointer over the link, how can I hide the URL? or how to hide the Servlet
    Url and params?If your JSP is providing the links as anchor tags (i.e. '<a href=...') then their is really very little that can ultimately be done about it.  Some JavaScript and CSS can be thrown in to keep the link from showing up in the browser's "info line".  However, unless you also throw in some script to also keep the user from being able to view the page source, this is only going to superfically "mask" the information and not really "hide" it.  Yet, even with disabling "view source" the user can still also disable JavaScript in the browser making all this moot. ;)
    A better solution to the matter is to move the "linking" from the client over to the server instead. Spend some time investigating the Front Controller pattern (see http://java.sun.com/blueprints/patterns/FrontController.html), and RequestDispatcher. Using 'buttons' in your JSP to signal views to the controller and session objects to store parameters already known to your application will take your application a lot farther in the long run than embedding HTML links in your front JSP. ;)
    Regards,
    Tony "Vee Schade" Cook

Maybe you are looking for

  • Problems with Apache Commons Validator

    Hello there, I got a quiet big problem using the a.m. validation framework. When defining a validation rule for a property like this: <formset> <form name="testForm"> <field property="firstName" depends="isEmail"> <arg0 key="testForm.firstname"/> </f

  • Is it possible to change the costing from moving average to standard??

    hey all, i wana know is it possible to change the costing from moving average to standard or vice-versa in the item master?? cheers

  • Oracle 10g.. log_archive_dest... query...

    Hi All, I created a new 10g database on my machine by default it was in noarchivelog mode. I converted my database in archive log mode.. by default it was archiving in db_recovery_file_dest But as it got full.. It stopped archiving... alter system se

  • Policies on specific time range

    Does Ironport has in the plan to set the policies to be applied in a specific time ranges, like apply a specific policy on morning then set another one at night? This feature is in the websense & smart filter and should be there in Ironport

  • BLOBs in JDBC

    Is there any way at all that a blob may be created and passed into a packaged stored procedure? The only working solutions I have seen involve passing the blob into a table directly and then calling an sp with a ref to the table. We could receive a L