我是一名编程 II 学生,也是第一次发帖者。一个很可能是一个非常简单的问题却让我困惑了太久。
*问题#3。 一个经过充分研究的事实是,在洗手间的男士通常更喜欢通过占据最长的未占用位置序列的中间来最大化他们与已占用隔间的距离。例如,考虑十个摊位是空的情况。
第一个访客会占据中间位置:
_ _ _ _ _ X _ _ _ _
下一位访客将在左侧空白区域的中间。
_ _ X _ _ X _ _ _ _
用 Java 编写一个程序,读取摊位的数量,然后在摊位填满时以上面给出的格式打印图表,一次一个。提示:使用 boolean 值数组来指示摊位是否有人。
public class MenStall
{
public static int nextStall(boolean[] stalls) { . . . }
public static void printStalls(boolean[] stalls) {. . . }
. . .
}
摊位数量 = 10 的输出示例
_ _ _ _ X _ _ _ _
_ _ _ _ X _ X _ _
_ X _ _ X _ _ X _ _
_ X _ _ X _ _ X X _
_ X _ _ X X _ X X _
_ X X _ X X _ X X _
_ X X _ X X _ X X X
_ X X _ X X X X X X
_ X X X X X X X X X
X X X X X X X X X X
我假设最简单的方法(本学期传授给我们的编程知识很少)是通过将数组的结尾和数组的开头声明为变量,并找到中间点通过从结尾减去开头并除以二。不幸的是,除此之外我被困住了。我不太精通编码术语,为此我深表歉意。我想展示我在解决这个问题上的尝试会更简单:
public class MenStall
{
public static int position = 0;
public static int nextStall = 0;
public static boolean[] stalls = new boolean[10];
public static final int TRUE_END = stalls.length;
public static final int TRUE_START = 0;
public static int start = TRUE_START;
public static int end = TRUE_END;
public static final int TRUE_MID = (TRUE_END - TRUE_START) / 2;
public static int mid = TRUE_MID;
public static int nextStall(boolean[] stalls)
{
if (position == 0)
{
nextStall = mid;
}
else
{
if (position % 2 == 1)
{
end = mid;
mid = (end - start) / 2;
nextStall = mid;
}
else if (position % 2 == 0)
{
mid = (end - start) / 2 + TRUE_MID;
nextStall = mid;
end = mid;
mid = (TRUE_END - TRUE_START) / (int)Math.pow(2,position);
}
}
position++;
return nextStall;
}
public static void printStalls(boolean[] stalls)
{
String[] s1 = new String[stalls.length];
while (position < stalls.length)
{
nextStall(stalls);
stalls [nextStall] = true;
for (int i = 0; i < stalls.length; i++)
{
if(stalls[i] == true)
{
s1[i] = "x";
}
else
{
s1[i] = "_";
}
}
System.out.println(Arrays.toString(s1));
}
}
public static void main(String[] args)
{
printStalls(stalls);
}
}
在 nextStall 方法的最后,我几乎只是在玩弄我陷入困境的数字。我当然付出了最大的努力,甚至不得不向教授申请延期,但我这辈子都想不通。任何指导将不胜感激。谢谢!
最佳答案
在我看来,使用 BitSet 它比 boolean[] 数组更简单,因为 BitSet 具有预定义方法 nextSetBit 返回(如其名称所示)下一个设置位。我认为,分而治之的策略对你的任务来说是不必要的。问题可以这样解决:
public static void main(String[] args) {
int numStalls = 10; // get it from user input if you like
BitSet bs = new BitSet();
// set the leftmost and the rightmost bits (which represent walls)
bs.set(0);
bs.set(numStalls+1);
// now we have 10 bits gap, which represent stalls
// like this: X__________X
for(int i=0; i<numStalls; i++) {
bs.set(nextStall(bs));
printStalls(bs);
}
}
public static int nextStall(BitSet bs) {
int bestPos = 0, maxDist = bs.nextSetBit(0);
// iterate over the set bits
for(int pos = maxDist; pos != -1; pos = bs.nextSetBit(pos+1)) {
int dist = bs.nextSetBit(pos+1) - pos;
// track the position of the stall with biggest gap on the right
if(dist > maxDist) {
maxDist = dist;
bestPos = pos;
}
}
// return the position on the middle of the best gap
return bestPos+maxDist/2;
}
public static void printStalls(BitSet bs) {
StringBuilder sb = new StringBuilder();
// Iterate over all the bit positions except the walls
// walls have positions 0 and bs.length()
for(int i=1; i<bs.length()-1; i++) {
sb.append(bs.get(i) ? "X" : "_");
}
System.out.println(sb);
}
如果允许 Java-8,解决方案可以更短:
public static int nextStall(BitSet bs) {
// Find the position of the stall (or wall)
// For which the next stall/wall is the most distant
// bs.stream() returns stream of positions of the set bits
int pos = bs.stream().boxed()
.max(Comparator.comparingInt(v -> bs.nextSetBit(v+1) - v)).get();
// Return the middle position in the gap
return (pos+bs.nextSetBit(pos+1))/2;
}
public static void printStalls(BitSet bs) {
// Iterate over all the bit positions except the walls
// walls have positions 0 and bs.length()
System.out.println(IntStream.range(1, bs.length() - 1)
.mapToObj(idx -> bs.get(idx) ? "X" : "_").collect(Collectors.joining()));
}
关于java - 小便器算法 - 一个简单的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645046/
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir