Skip to content

Commit

Permalink
- Added Swift solution to the "Lines Range" task.
Browse files Browse the repository at this point in the history
  • Loading branch information
manwar committed Aug 5, 2020
1 parent 05aee9e commit 6c629ee
Show file tree
Hide file tree
Showing 2 changed files with 182 additions and 0 deletions.
82 changes: 82 additions & 0 deletions challenge-072/mohammad-anwar/swift/ch-2.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import Foundation

/*
Perl Weekly Challenge - 072

Task #2: Lines Range

https://perlweeklychallenge.org/blog/perl-weekly-challenge-072
*/

enum ParamError: Error {
case missingFile
case missingA
case missingB
case invalidA
case invalidB
}

do {
let paramCount:Int = Int(CommandLine.argc)

if paramCount <= 1 {
throw ParamError.missingFile
}

if paramCount <= 2 {
throw ParamError.missingA
}

if paramCount <= 3 {
throw ParamError.missingB
}

let fileName:String = CommandLine.arguments[1]
let a:Int = Int(CommandLine.arguments[2])!
let b:Int = Int(CommandLine.arguments[3])!

if a <= 0 || a > b {
throw ParamError.invalidA
}
if b <= 0 {
throw ParamError.invalidB
}

let ranges:[String] = linesRange(fileName, a, b)
print(ranges.joined(separator: "\n"))
}
catch ParamError.missingFile {
print("Missing file.")
}
catch ParamError.missingA {
print("Missing A.")
}
catch ParamError.missingB {
print("Missing B.")
}
catch ParamError.invalidA {
print("Invalid A.")
}
catch ParamError.invalidB {
print("Invalid B.")
}
catch let error {
print(error)
}

//
//
// Function

func linesRange(_ fileName:String, _ a:Int, _ b:Int) -> [String] {

let contents = try! String(contentsOfFile: fileName)
let lines = contents.split(separator:"\n")

var ranges = [String]()
for i in a-1...b-1 {
ranges.append(String(lines[i]))
}

return ranges
}
100 changes: 100 additions & 0 deletions challenge-072/mohammad-anwar/swift/input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
L1
L2
L3
L4
L5
L6
L7
L8
L9
L10
L11
L12
L13
L14
L15
L16
L17
L18
L19
L20
L21
L22
L23
L24
L25
L26
L27
L28
L29
L30
L31
L32
L33
L34
L35
L36
L37
L38
L39
L40
L41
L42
L43
L44
L45
L46
L47
L48
L49
L50
L51
L52
L53
L54
L55
L56
L57
L58
L59
L60
L61
L62
L63
L64
L65
L66
L67
L68
L69
L70
L71
L72
L73
L74
L75
L76
L77
L78
L79
L80
L81
L82
L83
L84
L85
L86
L87
L88
L89
L90
L91
L92
L93
L94
L95
L96
L97
L98
L99
L100

0 comments on commit 6c629ee

Please sign in to comment.