2014年10月2日木曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 11(Storing Data Using Other Collection Types)、11.8(Exercises) 1.をSwiftで考えてみる。

11.8(Exercises) 1.

コード(Xcode)

main.swift

//
//  main.swift
//  sample1
//
//  Created by kamimura on 10/2/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

func makeRandArray() -> [UInt32] {
    var result:[UInt32] = []
    for x in 0..<20 {
        result.append(arc4random() % 10 + 1)
    }
    return result
}

func index(num:Int, nums:[Int]) -> Int? {
    for i in 0..<nums.count {
        if num == nums[i] {
            return i
        }
    }
    return nil
}

func findDups(nums:[Int]) -> [Int] {
    var nums1:[Int] = []
    var nums2:[Int] = []
    
    for num in nums {
        if index(num, nums1) != nil {
            if index(num, nums2) == nil {
                nums2.append(num)
            }
        } else {
            nums1.append(num)
        }
    }
    return nums2
}

let nums1:[Int] = makeRandArray().map({(n:UInt32) in Int(n)})
let nums2:[Int] = makeRandArray().map({(n:UInt32) in Int(n)})

println(nums1)
println(findDups(nums1))

println(nums2)
println(findDups(nums2))

入出力結果(Console Output)

[1, 7, 9, 7, 2, 1, 7, 9, 2, 6, 1, 6, 1, 3, 10, 1, 5, 10, 5, 8]
[7, 1, 9, 2, 6, 10, 5]
[7, 5, 8, 4, 4, 1, 8, 3, 7, 9, 9, 4, 9, 10, 8, 6, 10, 9, 2, 7]
[4, 8, 7, 9, 10]
Program ended with exit code: 0

0 コメント:

コメントを投稿