IT公司100题-6-根据上排给出十个数,在其下排填出对应的十个数

问题描述:

给你10分钟时间,根据上排给出十个数,在其下排填出对应的十个数
要求下排每个数都是先前上排那十个数在下排出现的次数。
上排的十个数如下:
【0,1,2,3,4,5,6,7,8,9】

举一个例子,
数值: 0,1,2,3,4,5,6,7,8,9
分配: 6,2,1,0,0,0,1,0,0,0
0在下排出现了6次,1在下排出现了2次,
2在下排出现了1次,3在下排出现了0次….
以此类推..  

问题分析:

它的原型跟八皇后有点类似,都是用回溯递归的方法去一次一次尝试,直到找出正确解。

具体的想法是:不断的去从下排数组中捉取在上排数组中对应位置中出现的个数,如果个数不对就更新下排数组中对应的值,只到找到正确值。(下排数组先初始为任意值)

如:

上排数组A:0,1,2,3,4,5,6,7,8,9
下排数组B:0,1,2,3,4,5,6,7,8,9
从上牌数组Index = 0开始,A[0] = 0,0在下排数组中的个数为1,那么下排数组B此时就要更新为:1,1,2,3,4,5,6,7,8,9

Index = 1, A[1] = 1, 1在下排数组中的个数为2,那么下排数组B此时就要更新为:1,2,2,3,4,5,6,7,8,9,从此不断的往下进行,只要找不到正确值就一直往下进行,如果Index >= 数组长度时,那么重新恢复Index = 0再往下进行测试直到找出正确解。

但这好像只能解决如上所述的情况,即连续的N个数。

代码实现:

package oschina.IT100;
/**
 * @project: oschina
 * @filename: IT6.java
 * @version: 0.10
 * @author: JM Han
 * @date: 21:46 2015/11/2
 * @comment: 数值: 0,1,2,3,4,5,6,7,8,9
 *           分配: 6,2,1,0,0,0,1,0,0,0
 * @result:
 */

import java.util.ArrayList;
import static tool.util.*;

public class IT6 {
   public static final int NUM = 10;
   ArrayList<Integer> lsta = new ArrayList<Integer>();
   ArrayList<Integer> lstb = new ArrayList<Integer>();
   boolean success;
   public IT6(){
      success = false;
      for (int i = 0; i < NUM; i++){
         lsta.add(i);
         lstb.add(i);
      }
   }
   ArrayList getB(){
      while(success != true){
         setNextB();
      }
      return lstb;
   }
   void setNextB(){
      boolean flag =true;
      for (int i=0; i < NUM; i++){
         int f = getFrequency(i);
         if(lstb.get(i) != f){
            lstb.set(i, f);
            flag = false;
         }
      }
      success = flag;
   }
   int getFrequency(int value){
      int count = 0;
      for(int i = 0; i < NUM; i++){
         if(lstb.get(i) == value)
            count++;
      }
      return count;
   }
   public static void main(String[] args) {
      IT6 test = new IT6();
      ArrayList<Integer> res = test.getB();
      printGenericIterator(test.lsta.iterator());
      System.out.println();
      printGenericIterator(test.lstb.iterator());

   }



}

代码输出:

0 1 2 3 4 5 6 7 8 9 
6 2 1 0 0 0 1 0 0 0


转载于:https://my.oschina.net/jimmyhan/blog/525055

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值