查找最大数量

如何解决查找最大数量

我有两个阵列和一辆卡车。我必须找出一辆卡车可以容纳多少个单元。这是数组:

boxes = [3,1,6]
units_per_box = [2,7,4]
truck_size = 6

每个箱子都一样大小,卡车可以装那么多箱子。我必须找出的是卡车上可以装的最大部件数量。这是我到目前为止的内容:

array = []
hash = Hash[boxes.zip units_per_box] => {3=>2,1=>7,6=>4}
hash.each { |k,v| k.times { array << v } } => [2,2,4,4]

现在,我必须在array中找到适合卡车的最大物品数量。数组中的每个数字都是一个盒子,卡车将容纳6个盒子。仅查看数字,您就可以看到数字应该是27,因为7 +(4 * 5)=27。我如何在代码中弄清楚呢?我什至朝着正确的方向前进吗?

解决方法

似乎您在这里有多个红色鲱鱼。首先,这似乎并不重要 每个项目有多少盒,因为目标是获得最多的单位 卡车。

第二,卡车的尺寸本身似乎并不重要。如果以前的假设 是正确的,那么我们只关心每盒中的单位以及那里的最大数量 无论卡车的大小如何,始终保持住。

如果所有这些假设都是正确的,则 public class DeviceCodeAuthProvider : IAuthenticationProvider { private IConfidentialClientApplication _confidentialClientApplication; private string[] _scopes; private IAccount _userAccount; public DeviceCodeAuthProvider(string tenantId,string appId,string clientSecret,string[] scopes) { _scopes = scopes; _confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(appId) .WithTenantId(tenantId) .WithClientSecret(clientSecret) .Build(); } public async Task<string> GetAccessToken() { // If there is no saved user account,the user must sign-in if (_userAccount == null) { try { var task = _confidentialClientApplication.AcquireTokenForClient(_scopes).ExecuteAsync(); task.Wait(); var result = task.Result; _userAccount = result.Account; return result.AccessToken; } catch (Exception exception) { Console.WriteLine($"Error getting access token: {exception.Message}"); return null; } } else { var result = await _confidentialClientApplication .AcquireTokenSilent(_scopes,_userAccount) .ExecuteAsync(); return result.AccessToken; } } public async Task AuthenticateRequestAsync(HttpRequestMessage requestMessage) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer",await GetAccessToken()); } } public class GraphHelper { private static GraphServiceClient graphClient; public static void Initialize(IAuthenticationProvider authProvider) { graphClient = new GraphServiceClient(authProvider); } public static User GetMeAsync() { try { // GET /me Task<User> tu = graphClient.Me.Request().GetAsync(); tu.Wait(); User u = tu.Result; return u; } catch (ServiceException ex) { Console.WriteLine($"Error getting signed-in user: {ex.Message}"); return null; } catch (Exception ex) { Console.WriteLine($"Error getting signed-in user: {ex.Message}"); return null; } } } units_per_box[1]将是 在这种情况下的答案。同样,似乎我们可能需要一些 在这里澄清。我将根据需要删除和/或编辑我的问题。

,

您非常接近-您拥有整数数组,并且想要N大,对吧?

就是这样:

fits_in_truck = [2,2,7,4,4].sort.last(n)
units_in_truct = fits_in_truck.sum

总体上,用一些更有意义的名称来说明问题:

num_per_type = [3,1,6]
box_unit_types = [2,4]
truck_size = 6

box_type_tally = box_unit_types.zip(num_per_type).to_h

boxes = box_type_tally.flat_map do |box_units,num_boxes|
  [box_units] * num_boxes
end

loadable_boxes = boxes.sort.last(truck_size)
deliverable_units = loadable_boxes.sum
,

据我了解,红色,绿色和蓝色这三种类型的盒子都有各自的编号。每个框都有一个取决于其颜色的指定值。卡车具有给定数量的箱子的容量。问题是要确定将每种颜色的多少个箱子装载到卡车上,以使总价值最大化。如果仅需要最大总价值,我将在后面进行简化。

可以通过以下方法确定最佳解决方案。

def load_plan(nbr_boxes,box_value,truck_capacity)
  nbr_boxes.each_index.sort_by { |i| -box_value[i] }.
            each_with_object(Hash.new(0)) do |i,h|
              h[i] = [nbr_boxes[i],truck_capacity].min
              truck_capacity -= h[i]
              break(h) if truck_capacity.zero?
            end
end
nbr_boxes = [3,6]
box_value = [2,4]
truck_capacity = 6
plan = load_plan(nbr_boxes,truck_capacity)
  #=> {1=>1,2=>5}
plan[0]
  #=> 0 
plan[1]
  #=> 1 
plan[2]
  #=> 5 

最大值由下式给出:

plan.sum { |i,n| n * box_value[i] }
  #=> 27

步骤如下。

a = nbr_boxes.each_index.sort_by { |i| -box_value[i] }
  #=> [1,0]

这表明索引1的框的值最大,索引0的框的值最小。

为了说明其余的计算,我将使用puts语句对代码加盐。

a.each_with_object(Hash.new(0)) do |i,h|
  puts "i=#{i},h=#{h},nbr_boxes[#{i}]=#{nbr_boxes[i]}"
  h[i] = [nbr_boxes[i],truck_capacity].min
  truck_capacity -= h[i]
  puts "  h=#{h},truck_capacity=#{truck_capacity}"
  puts "  break #{h} as truck_capacity=0" if truck_capacity.zero? 
  break(h) if truck_capacity.zero?
end
  #=> {1=>1,2=>5} 

显示以下内容。

i=1,h={},nbr_boxes[1]=1
  h={1=>1},truck_capacity=5
i=2,h={1=>1},nbr_boxes[2]=6
  h={1=>1,2=>5},truck_capacity=0
  break {1=>1,2=>5} as truck_capacity=0

通过将块变量h所保存的哈希定义为Hash.new(0),我们可以编写

plan[0]
  #=> 0

即使0不是plan的键。这使用Hash::new的形式,该形式带有一个参数且没有任何块。该参数称为默认值。通常,如此处所示,它设置为零。这就是说,如果定义了哈希h = Hash.new(0),并且h[k]没有键0,则h将返回默认值(k)。 / p>

请注意,最后一条语句break(h) if truck_capacity.zero?是可选的。我包括它只是为了加快计算速度。

如果不需要每种类型的要装入的盒子的最佳数量,而仅是最佳总值,则可以进行一些简化。以下是@engineersmnky在对该问题的评论中建议的方法的细微变化:

def optimal_value(nbr_boxes,truck_capacity)
  nbr_boxes.each_index.
            flat_map { |i| [box_value[i]] * nbr_boxes[i] }.
            sort.
            last(truck_capacity).sum
end
optimal_value(nbr_boxes,truck_capacity)
  #=> 27

请注意,即使卡车没有满载,这也可以工作:

truck_capacity = 100
[2,4].last(truck_capacity)
  #=> [2,4]

在设计应用程序时,可以考虑将nbr_boxesbox_value替换为如下所示的哈希数组。

boxes = [
  { name: "A",nbr: 3,value: 2 },{ name: "B",nbr: 1,value: 7 },{ name: "C",nbr: 6,value: 4 }
]

然后写:

def load_plan(boxes,truck_capacity)
  boxes.sort_by { |box| -box[:value] }.
        each_with_object(Hash.new(0)) do |box,h|
          nbr_to_load = [box[:nbr],truck_capacity].min
          h[box[:name]] = nbr_to_load
          truck_capacity -= nbr_to_load
          break(h) if truck_capacity.zero?
        end
end
plan = load_plan(boxes,truck_capacity)
  #=> {"B"=>1,"C"=>5}
plan["A"]
  #=> 0

最大值由下式给出:

boxes.sum { |box| plan[box[:name]] * box[:value] }
  #=> 27

如果仅需要最大值:

def optimal_value(boxes,truck_capacity)
  boxes.flat_map { |box| [box[:value]] * box[:nbr] }.
        sort.
        last(truck_capacity).
        sum
end
optimal_value(boxes,truck_capacity)
  #=> 27

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-