草庐IT

swift - 难以让 readLine() 在 HackerRank 上按预期工作

coder 2023-09-15 原文

我正在尝试提交 HackerRank Day 6 Challenge 30 天的代码。

我能够在 Xcode Playground 中毫无问题地完成任务,但是 HackerRank 的网站说我的方法没有输出。由于浏览器不稳定,我昨天遇到了一个问题,但清理缓存、从 Safari 切换到 Chrome 等似乎无法解决我在这里遇到的问题。我认为我的问题在于 inputString

Task Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

Input Format

The first line contains an integer, (the number of test cases). Each line of the subsequent lines contain a String, .

Constraints

  • 1 <= T <= 10
  • 2 <= length of S < 10,000

Output Format

For each String (where 0 <= j <= T-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.

这是我要提交的代码:

import Foundation

let inputString = readLine()!

func tweakString(string: String) {
    // split string into an array of lines based on char set
    var lineArray = string.components(separatedBy: .newlines)

    // extract the number of test cases
    let testCases = Int(lineArray[0])

    // remove the first line containing the number of unit tests
    lineArray.remove(at: 0)

    /*
    Satisfy constraints specified in the task
     */
    guard lineArray.count >= 1 && lineArray.count <= 10 && testCases == lineArray.count else { return }

    for line in lineArray {
        switch line.characters.count {
        // to match constraint specified in the task
        case 2...10000:
            let characterArray = Array(line.characters)
            let evenCharacters = characterArray.enumerated().filter({$0.0 % 2 == 0}).map({$0.1})
            let oddCharacters = characterArray.enumerated().filter({$0.0 % 2 == 1}).map({$0.1})

            print(String(evenCharacters) + " " + String(oddCharacters))
        default:
            break
        }
    }
}

tweakString(string: inputString)

我认为我的问题在于 inputString。我“按原样”使用它并在我的方法中对其进行格式化。我找到了第 6 天的解决方案,但我似乎无法在 Swift 中找到任何当前的解决方案。

感谢阅读。我欢迎关于如何让这件事通过的想法。

最佳答案

readLine() 从标准输入中读取单行,这 意味着您的 inputString 仅包含来自 输入数据。您必须在循环中调用 readLine() 才能获取 剩余的输入数据。

所以你的程序看起来像这样:

func tweakString(string: String) -> String {
    // For a single input string, compute the output string according to the challenge rules ...
    return result
}

let N = Int(readLine()!)! // Number of test cases

// For each test case:
for _ in 1...N {
    let input = readLine()!
    let output = tweakString(string: input)
    print(output)
}

(强制展开在这里是可以接受的,因为格式 输入数据记录在挑战描述中。)

关于swift - 难以让 readLine() 在 HackerRank 上按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42025437/

有关swift - 难以让 readLine() 在 HackerRank 上按预期工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  4. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  5. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  6. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  7. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  8. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

  9. ruby-on-rails - ruby 日期方程不返回预期的真值 - 2

    为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998

  10. ruby - `rescue $!` 是如何工作的? - 2

    我知道全局变量$!包含最新的异常对象,但我对下面的语法感到困惑。谁能帮助我理解以下语法?rescue$! 最佳答案 此构造可防止异常停止您的程序并使堆栈跟踪冒泡。它还会将该异常作为值返回,这很有用。a=get_me_datarescue$!在此行之后,a将保存请求的数据或异常。然后您可以分析该异常并采取相应措施。defget_me_dataraise'Nodataforyou'enda=get_me_datarescue$!puts"Executioncarrieson"pa#>>Executioncarrieson#>>#更现实的

随机推荐