这一篇本来就是想跟大家分享下我做的第一个小玩意–模拟双色球,但是期间会需要用到数组去重,所以我就封装了一个函数,这个去重的思路是我独立想出来的,比较简洁高效,我很引以为豪,特地分享给大家。
一、数组去重函数
//删原来位置的数后,后边的数补到原来的位置,于是下次还要和原来位置的数比,于是要减 1
func removeDuplicates(inout arr:[Int]) -> [Int]{
for i in 0..<arr.count{
var j = i
while j<arr.count-1{
j += 1
if arr[i] == arr[j]{
arr.removeAtIndex(j)
j = j - 1
}
else{
continue
}
} //while
}// for
return arr
}
二、模拟双色球游戏
规则:
流程:
1、用户输入自己猜的数 购买彩票
2、开奖器的制作 :
红球有32个:1-32 ,蓝球有6个:1-16,每次开奖开出6个
不重复的红球和一个蓝球
3、查看是否中奖
import Foundation
func scanf()->Int{
//控制台输入
let stdin = NSFileHandle.fileHandleWithStandardInput()
var input = NSString(data: stdin.availableData, encoding: NSUTF8StringEncoding) as! String
input.removeAtIndex(input.endIndex.predecessor())
return (input as NSString).integerValue
}
// 查重 并删除 的函数
func removeDuplicates(inout arr : [Int])->[Int]{
for i in 0..<arr.count{
var j = i
while j<arr.count-1{
j += 1
if arr[i] == arr[j]{
arr.removeAtIndex(j)
j = j - 1
}
else{
continue
}
} //while
}// for
return arr
}
// 1、用户输入自己猜的数 购买彩票
var URed = Array<Int>(count:6 , repeatedValue:0)
print("您要买的红球号码为:\n")
for k in 0..<6{
URed[k] = scanf()%32
}
print("您要买的蓝球号码为:\n")
var UBlue : Int = scanf()%16
// 2、开奖器的制作
// (1)、输出红球,放在一个数组中
var red = Array<Int>(count:6 , repeatedValue:0) //初始化一个固定个数的数组
//var red = Array<Int>()
for i in 0..<6{
let num = Int(arc4random()%32 + 1) //先输入6个红球
red[i] = num
}
removeDuplicates(&red) // 去重,不够6个
while red.count < 6{ // 继续输入 去重 ,知道 拿到6个不重复
var red1 = Array<Int>(count:6-red.count, repeatedValue:0)
for j in 0..<red1.count{
red1[j] = Int(arc4random()%32 + 1)
}
removeDuplicates(&red1)
red += red1
}
sort(&red) //进行排序
print("本次开奖结果红球是:\(red)\n")
// (2)输出蓝球
let blue = Int(arc4random()%16 + 1)
print("本次开奖结果蓝球是:[\(blue)]\n")
// 3、查看是否中奖
var Redcount = 0
for m in 1...5{
for n in 1...5{
if red[m] == URed[n]{
Redcount += 1
}
}
}
// 一等奖
if Redcount == 6 && blue == UBlue{
print("恭喜您,您获得了一等奖")}
if Redcount == 6 && blue != UBlue{
print("恭喜您,您获得了二等奖")
}
if Redcount == 5 && blue == UBlue{
print("恭喜您,您获得了三等奖")
}
if (Redcount == 5 && blue != UBlue)||(Redcount == 4 && blue == UBlue){
print("恭喜您,您获得了四等奖")
}
if (Redcount == 3 && blue == UBlue)||(Redcount == 4 && blue != UBlue){
print("恭喜您,您获得了五等奖")
}
if (Redcount == 2 && blue == UBlue)||(Redcount == 1 && blue == UBlue)||(Redcount == 0 && blue == UBlue){
print("恭喜您,您获得了一等奖")
}
else{
print("不好意思您没中奖")
}