产品的其他数字采访使用蛮力回答

时间:2016-11-16 11:02:18

标签: java algorithm

我试图用蛮力来回答这个问题,这样我就可以理解发生了什么:

https://www.interviewcake.com/question/java/product-of-other-numbers

但问题是我不明白为什么我的逻辑不起作用。这是我到目前为止所尝试的:

public class EveryInteger {

    public static void main(String[] args) {

        int a1[] = {1, 7, 3, 4};
         int a2[] = new int[4];
          for(int i =0; i<a1.length; i++){
            int index = a1[i];
            int sum = 0;

            for(int j =0; j<a1.length; j++){
                if(a1[i]==a1[j]){
                    continue;
                }

                sum = index * a1[j];
                a2[i] = sum;
                System.out.println(a2[i]);
            }
          }
    }

任何人都可以告诉我如何使用两个for循环来解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

这里有几个问题:

<portlet:renderURL var="manageRelationsURL"
windowState="<%=LiferayWindowState.NORMAL.toString()%>">
<portlet:param name="action" value="manageRelations" />
</portlet:renderURL>

<%PortletURL iteratorURL = renderResponse.createRenderURL();
iteratorURL.setParameter("action", "manageRelations");
%>

    <%
PortalPreferences portalPrefs = PortletPreferencesFactoryUtil.getPortalPreferences(request);
String orderByCol = ParamUtil.getString(request, "orderByCol");
String orderByType = ParamUtil.getString(request, "orderByType");


if (Validator.isNotNull(orderByCol) && Validator.isNotNull(orderByType)) {
    portalPrefs.setValue("NAME_SPACE", "order-by-col", orderByCol);
    portalPrefs.setValue("NAME_SPACE", "order-by-type", orderByType);

} else {
    orderByCol = portalPrefs.getValue("NAME_SPACE", "order-by-col", "domainLabel");
    orderByType = portalPrefs.getValue("NAME_SPACE", "order-by-type", "asc");

}
 %>
<div style="">
<aui:form>
<liferay-ui:search-container delta="20" iteratorURL="<%=iteratorURL%>" emptyResultsMessage="There were not any match." orderByCol="<%= orderByCol %>" orderByType="<%= orderByType %>">
<liferay-ui:search-form
    page="/WEB-INF/jsp/localAdministration/relations/search.jsp"
    searchContainer="<%= searchContainer %>"
    servletContext="<%= this.getServletConfig().getServletContext() %>"
    showAddButton="true" />
    <liferay-ui:search-container-results>

        <%
        List<RelationInstance> relationList = UtilsAdministration.getRelationListCache(themeDisplay.getUserId(),0, UtilsAdministration.getRelationListCacheSize(themeDisplay.getUserId()));
        Collections.sort(relationList,RelationsComparator.getRelationsOrderByComparator(orderByCol, orderByType));

        results = ListUtil.subList(relationList, searchContainer.getStart(),   
                 searchContainer.getEnd());

           if(relationList.size()<searchContainer.getEnd()){
               results = ListUtil.subList(relationList, searchContainer.getStart(),   
                       relationList.size());
               total = relationList.size();
           }else{
               results = ListUtil.subList(relationList, searchContainer.getStart(),   
                       searchContainer.getEnd());
               total = relationList.size();
           }

           pageContext.setAttribute("results", results);
           pageContext.setAttribute("total", total);
        %>
        </liferay-ui:search-container-results>


    <liferay-ui:search-container-row className="RelationInstance" modelVar="aRelationInstance">
        <liferay-ui:search-container-column-text name="First" value="<%=aRelationInstance.getFirstLabel()%>" orderable="<%= true %>" orderableProperty="domainLabel"/>
        <liferay-ui:search-container-column-text name="Second" value="<%=aRelationInstance.getSecondLabel()%>" orderable="<%= true %>" orderableProperty="relationLabel"/>
        <liferay-ui:search-container-column-text name="Third" value="<%=aRelationInstance.getRangeLabel()%>" orderable="<%= true %>" orderableProperty="rangeLabel"/>
        <liferay-ui:search-container-column-jsp align="right" name="Acciones" path="/WEB-INF/jsp/localAdministration/relations/actionRelationButton.jsp"/>  
    </liferay-ui:search-container-row>
    <liferay-ui:search-iterator />
</liferay-ui:search-container>
</aui:form>
</div>

解决方案可能如下所示:

// defining an array like this is confusing because the type is not immediately clear, rather use int[] a1 = ...
int a1[] = {1, 7, 3, 4}; 
// a2 should always have the same length as a1, so use a1.length
int a2[] = new int[4];
for(int i =0; i<a1.length; i++){
    // index is a little confusing, since it's not the index but the value at i
    int index = a1[i];
    // sum is also confusing, since you're working with multiplication here
    // Additionally with multiplication involved, initialize that to 1
    int sum = 0;

    for(int j =0; j<a1.length; j++){
        // comparing only j and i would be sufficient here without accessing the array twice
        if(a1[i]==a1[j]){
            continue;
        }

        // Instead of accumulating the product you reassign it every time, effectively deleting the previous value.
        sum = index * a1[j];
        a2[i] = sum;
        System.out.println(a2[i]);
    }
}

结果符合要求:

int[] input = {1,7,3,4};
int[] output = new int[input.length];

for(int i = 0; i < input.length; i++) {
  // Accumulates the multiplications.
  int acc = 1;
  for(int j = 0; j < input.length; j++) {
    // check, if not at the same index.
    if(j != i) {
      // only then multiply the current number with the accumulator.
      acc *= input[j];
    }
  }
  // finally write the accumulated product to the output array.
  output[i] = acc;
}

System.out.println(Arrays.toString(output));

答案 1 :(得分:0)

您将sum分配给a2并在内循环中打印,这是不正确的。尝试在外循环中执行此操作:

public class EveryInteger {

    public static void main(String[] args) {
        int a1[] = {1, 7, 3, 4};
         int a2[] = new int[4];
          for(int i =0; i<a1.length; i++){
            int sum = 1;

            for(int j =0; j<a1.length; j++){
                if(a1[i]==a1[j]){
                    continue;
                }
                sum *= a1[j];
            }
            a2[i] = sum;
            System.out.println(a2[i]);
          }
    }
}