Compare Array [Triplets] - ios
I'm trying to complete this
a = [5, 6, 7]
b = [3, 6, 10]
Now, let's compare each individual score:
a[0] > b[0], so Alice receives point.
a[1] == b[1], so nobody receives a point.
a[2] < b[2] , so Bob receives point.
Alice's comparison score is 1, and Bob's comparison score is 1. Thus, we have to print 1 1 (Alice's comparison score followed by Bob's comparison score) on a single line.
I did it by this way:
var a = [5, 6, 7]
var b = [3, 6, 10]
let pointsAlice = (a[0] > b[0] ? 1: 0) + (a[1] > b[1] ? 1: 0) + (a[2] > b[2] ? 1: 0)
let pointsBob = (a[0] < b[0] ? 1: 0) + (a[1] < b[1] ? 1: 0) + (a[2] < b[2] ? 1: 0)
print("\(pointsAlice) \(pointsBob)")
But it is showing as an incorrect answer(Hackerrank).
Is my way correct or is there any other way to solve this ?
Please try this ...
let a = readLine()!.components(separatedBy: " ").flatMap { Int($0) }
let b = readLine()!.components(separatedBy: " ").flatMap { Int($0) }
let aResult = zip(a, b).filter(>).count
let bResult = zip(b, a).filter(>).count
//Final Result Status
print(aResult, bResult)
I guess u concentrated on explanation more :p
Try this:
let arrA = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let arrB = readLine()!.components(separatedBy: " ").map{ Int($0)! }
var aliceScore = 0
var bobScore = 0
for index in 0...2{
if (arrA[index] > arrB[index]){
aliceScore += 1
}
if (arrA[index] < arrB[index]){
bobScore += 1
}
}
print("\(aliceScore)" + " " + "\(bobScore)")
This was my solution. Trying to learn how the reduce func works.
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
var total = [0,0]
for x in 0..<a.count {
if a[x] > b[x] {
total[0] += 1
} else if a[x] < b[x] {
total[1] += 1
}
}
return aTotal
}
Why not just use higher order functions like reduce?
let a = [5, 6, 7]
let b = [3, 6, 10]
let pointsAlice = zip(a, b).reduce(0, combine: { $0 + ($1.0 > $1.1 ? 1 : 0) } )
let pointsBob = zip(b, a).reduce(0, combine: { $0 + ($1.0 > $1.1 ? 1 : 0) } )
print("\(pointsAlice) \(pointsBob)") // 1 1
Do not hard code like this
(a[0] > b[0] ? 1: 0) + (a[1] > b[1] ? 1: 0) + (a[2] > b[2] ? 1: 0)
Imagine if the array has 1,000 or more elements!!!
I think the simplest solution is:
var alicePoints = 0
var bobPoints = 0
for i in 0..<A.count {
if A[i] > B[i] {
alicePoints += 1
} else if A[i] < B[i] {
bobPoints += 1
}
}
print("\(alicePoints) \(bobPoints)")
And the more elegant solution is the one from #koropok above (I upated for Swift 3.x)
let bobPoints = zip(B, A).reduce(0) { $0 + ($1.0 > $1.1 ? 1 : 0) }
let alicePoints = zip(A, B).reduce(0) { $0 + ($1.0 > $1.1 ? 1 : 0) }
print("\(alicePoints) \(bobPoints)")
Here is the updated Answer for comparing Triplets
Let's say if we have
var a = [5, 6, 7]
var b = [3, 6, 10]
Then
// compareTriplets function
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
let bobPoints = zip(b, a).reduce(0) { $0 + ($1.0 > $1.1 ? 1 : 0) }
let alicePoints = zip(a, b).reduce(0) { $0 + ($1.0 > $1.1 ? 1 : 0) }
print("Points earned by Alice and Bob : \(alicePoints) \(bobPoints)")
return [alicePoints, bobPoints]
}
Try this:
return [zip(a, b).reduce(0) {$0 + ($1.0 > $1.1 ? 1 : 0)},
zip(b, a).reduce(0) {$0 + ($1.0 > $1.1 ? 1 : 0)}]
In python, without considering the constraints proposed(ab >= 1 & ab<=100):
def compareTriplets(a, b):
i = 0
score = [0,0]
while i < 3:
if a[i] > b[i]:
score[0] = score[0] + 1
elif a[i] < b[i]:
score[1] = score[1] + 1
i = i + 1
return score
import java.util.*.;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int klice=0;
int bob=0;
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
b[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
if(a[i]>b[i]){
klice++;
} else if(b[i]>a[i]){
bob++;
}
}
System.out.println(klice +" "+ bob);
}
}
Related
Hackerrank New Year Chaos Swift
I am trying to solve Hackerrank's New Year Chaos problem in Swift. https://www.hackerrank.com/challenges/new-year-chaos/problem It is about finding the number of bribes people made on a line waiting for a roller coaster ride. For example, there is a total of 3 bribes in this list [2, 1, 5, 3, 4]. Person 2 bribed person 1. Person 5 bribed person 3 and 4. If there are more than 2 bribes by a person, the line becomes "Too chaotic". I was able to get an exponential solution. However, I want to make it linear. func minimumBribes(q: [Int]) -> Void { var bribeCount = 0 var chaotic = false // for i in 0..<q.count { // if q[i] - (i + 1) > 2 { // chaotic = true // break // } // // for j in i + 1..<q.count { // if q[i] > q[j] { // bribeCount += 1 // } // } // } var i = 0 while i < q.count - 1 { if q[i] - (i + 1) > 2 { chaotic = true break } else if q[i] > i + 1 { bribeCount += (q[i] - (i + 1)) i += 1 } else if q[i] <= i + 1 && q[i] > q[i + 1] && q.indices.contains(i + 1) { bribeCount += 1 i += 1 } else { // q[i] < q[i + 1] i += 1 } } if chaotic { print("Too chaotic") } else { print(bribeCount) } } I commented out the exponential solution, which works. But the linear solution does not work and I cannot find out why. It works with the following arrays, [3,2,1,6,5,4], [2,5,1,3,4], [1,2,5,3,7,8,6,4], [1,3,4,2,7,6,5,9,8,11,10,14,13,12]. But there is a really long array in one of the test cases of the problem, which I do not get the correct answer with my linear solution. For this long array, I get 966 with my exponential solution but the linear solution prints 905. [2,1,5,6,3,4,9,8,11,7,10,14,13,12,17,16,15,19,18,22,20,24,23,21,27,28,25,26,30,29,33,32,31,35,36,34,39,38,37,42,40,44,41,43,47,46,48,45,50,52,49,51,54,56,55,53,59,58,57,61,63,60,65,64,67,68,62,69,66,72,70,74,73,71,77,75,79,78,81,82,80,76,85,84,83,86,89,90,88,87,92,91,95,94,93,98,97,100,96,102,99,104,101,105,103,108,106,109,107,112,111,110,113,116,114,118,119,117,115,122,121,120,124,123,127,125,126,130,129,128,131,133,135,136,132,134,139,140,138,137,143,141,144,146,145,142,148,150,147,149,153,152,155,151,157,154,158,159,156,161,160,164,165,163,167,166,162,170,171,172,168,169,175,173,174,177,176,180,181,178,179,183,182,184,187,188,185,190,189,186,191,194,192,196,197,195,199,193,198,202,200,204,205,203,207,206,201,210,209,211,208,214,215,216,212,218,217,220,213,222,219,224,221,223,227,226,225,230,231,229,228,234,235,233,237,232,239,236,241,238,240,243,242,246,245,248,249,250,247,244,253,252,251,256,255,258,254,257,259,261,262,263,265,264,260,268,266,267,271,270,273,269,274,272,275,278,276,279,277,282,283,280,281,286,284,288,287,290,289,285,293,291,292,296,294,298,297,299,295,302,301,304,303,306,300,305,309,308,307,312,311,314,315,313,310,316,319,318,321,320,317,324,325,322,323,328,327,330,326,332,331,329,335,334,333,336,338,337,341,340,339,344,343,342,347,345,349,346,351,350,348,353,355,352,357,358,354,356,359,361,360,364,362,366,365,363,368,370,367,371,372,369,374,373,376,375,378,379,377,382,381,383,380,386,387,384,385,390,388,392,391,389,393,396,397,394,398,395,401,400,403,402,399,405,407,406,409,408,411,410,404,413,412,415,417,416,414,420,419,422,421,418,424,426,423,425,428,427,431,430,429,434,435,436,437,432,433,440,438,439,443,441,445,442,447,444,448,446,449,452,451,450,455,453,454,457,456,460,459,458,463,462,464,461,467,465,466,470,469,472,468,474,471,475,473,477,476,480,479,478,483,482,485,481,487,484,489,490,491,488,492,486,494,495,496,498,493,500,499,497,502,504,501,503,507,506,505,509,511,508,513,510,512,514,516,518,519,515,521,522,520,524,517,523,525,526,529,527,531,528,533,532,534,530,537,536,539,535,541,538,540,543,544,542,547,548,545,549,546,552,550,551,554,553,557,555,556,560,559,558,563,562,564,561,567,568,566,565,569,572,571,570,575,574,577,576,579,573,580,578,583,581,584,582,587,586,585,590,589,588,593,594,592,595,591,598,599,596,597,602,603,604,605,600,601,608,609,607,611,612,606,610,615,616,614,613,619,618,617,622,620,624,621,626,625,623,628,627,631,630,633,629,635,632,637,636,634,638,640,642,639,641,645,644,647,643,646,650,648,652,653,654,649,651,656,658,657,655,661,659,660,663,664,666,662,668,667,670,665,671,673,669,672,676,677,674,679,675,680,678,681,684,682,686,685,683,689,690,688,687,693,692,691,696,695,698,694,700,701,702,697,704,699,706,703,705,709,707,711,712,710,708,713,716,715,714,718,720,721,719,723,717,722,726,725,724,729,728,727,730,733,732,735,734,736,731,738,737,741,739,740,744,743,742,747,746,745,750,748,752,749,753,751,756,754,758,755,757,761,760,759,764,763,762,767,765,768,766,771,770,769,774,773,776,772,778,777,779,775,781,780,783,784,782,786,788,789,787,790,785,793,791,792,796,795,794,798,797,801,799,803,800,805,802,804,808,806,807,811,809,810,814,812,813,817,816,819,818,815,820,821,823,822,824,826,827,825,828,831,829,830,834,833,836,832,837,839,838,841,835,840,844,842,846,845,843,849,847,851,850,852,848,855,854,853,857,856,858,861,862,860,859,863,866,865,864,867,870,869,868,872,874,875,871,873,877,878,876,880,881,879,884,883,885,882,888,886,890,891,889,893,887,895,892,896,898,894,899,897,902,901,903,905,900,904,908,907,910,909,906,912,911,915,913,916,918,914,919,921,917,923,920,924,922,927,925,929,928,926,932,931,934,930,933,935,937,939,940,938,936,943,944,942,941,947,946,948,945,951,950,949,953,952,956,954,958,957,955,961,962,963,959,964,966,960,965,969,968,971,967,970,974,972,976,973,975,979,977,981,982,978,980,983,986,984,985,989,988,987,990,993,991,995,994,997,992,999,1000,996,998] Please help me figure out what is wrong with my solution. Thanks in advance!!
Here is my solution which passes all the test cases :) func minimumBribes(q: [Int]) -> Void { var bCount = 0 var isChaotic = false for (key,value) in q.enumerated() { if (value - 1) - key > 2 { isChaotic = true break } for index in stride(from: max(0, value - 2), to: key, by: 1){ if q[index] > value { bCount += 1 } } } isChaotic ? print("Too chaotic") : print("\(bCount)") }
What you basically need to do is to first check if the element in each loop is on it's correct position. And if not you find out how much further is it from the right position if its greater than 2 you print "Too chaotic". Your solution is correct uptil this point. But if the difference is less than or equal to 2 then you need to increment the bribes and swap the indices to represent updated array. Furthermore if there are two swaps then you need to represent how the array would be effected by these 2 swaps and hence swap these values before the next iteration to ensure the array is in the condition it would be after these swaps. Please refer to my solution below. It passes for all test cases: func swapValues( arr:inout [Int],index:Int, times: Int, bribes:inout Int) -> Bool { if times == 0 { return false } if arr[index] > arr[index+1] { let temp = arr[index+1] arr[index+1] = arr[index] arr[index] = temp bribes = bribes + 1 return swapValues(arr: &arr, index: index+1, times: times-1,bribes: &bribes) }else{ var diff = abs(arr[index+1] - (index+2)) if diff > 2 { print("Too chaotic") return true } var tooChaotic = swapValues(arr: &arr, index: index+1, times: diff,bribes:&bribes) if tooChaotic { return true } return swapValues(arr: &arr, index: index, times: times, bribes: &bribes) } } func minimumBribes(q: [Int]) -> Void { var qC = q var bribes = 0 var i = 0 while i <= qC.count-1{ if i+1 == qC[i] { i = i + 1 continue } let diff = abs(qC[i] - (i+1)) if diff > 2 { print("Too chaotic") return } var tooChaotic = swapValues(arr: &qC, index: i, times: diff, bribes: &bribes) if tooChaotic { return } } print(bribes) }
I found this short and easy solution. func minimumBribes(q: [Int]) -> Void { var ans = 0 var shouldShow = true for i in stride(from: (q.count - 1), through: 0, by: -1) { if (q[i] - (i+1) > 2) { shouldShow = false break; } for j in stride(from: max(0, q[i] - 2), to: i, by: 1){ if q[j] > q[i] { ans += 1 } } } if shouldShow { print(ans) } else { print("Too chaotic") } } https://github.com/AnanthaKrish/example-ios-apps
how to use modifying for-loop in Swift 3.2?
I have a converted for-loop in Swift 3.2 that looks similar to this: for var i in 0..<char.characters.count { if(self.characters.count > len && ((currentIndex + length2323) < length)) { i = i - 1 } } But, It doesn't work properly. I want to continue loop when set value for i is i = i - 1 but this code getting out of loop And my previous Swift 2 code is : for(var i = 0 ; i < char.characters.count ; i += 1) { if(self.characters.count > len && ((currentIndex + length2323) < length)) { i = i - 1 } }
for (index, item) in char.enumerated() { //your loop }
Swift 4 syntax import UIKit var char = "char" var len = 9 var currentIndex = 1 var length2323 = 2323 var length = 17 for var i in 0..<char.count { if (self.count > len) && ((currentIndex + length2323) < length) { i = i - 1 } } Swift 3.2 syntax import UIKit var char = "char" var len = 9 var currentIndex = 1 var length2323 = 2323 var length = 17 for var i in 0..<char.characters.count { if (self.characters.count > len) && ((currentIndex + length2323) < length) { i = i - 1 } }
Find longest common substring of array of Strings
In my Swift 3.0 app, I want to determine the best name for something by finding the longest common substring of 6 to 12 strings. Example strings: ON/OFF office lights DIM office lights VALUE office lights FB office lights FB VALUE office lights Desired output: office lights I've come across multiple StackOverflow answers for the longest subsequence but haven't been able to adapt any of them to my needs.. Any help would be greatly appreciated!
I converted Java & C++ code into Swift 3 , collected from GeeksForGeeks Longest Common Subsequence & Longest Common Substring. It works ! class LongestCommon { // Returns length of LCS for X[0..m-1], Y[0..n-1] private static func lcSubsequence(_ X : String , _ Y : String ) -> String { let m = X.characters.count let n = Y.characters.count var L = Array(repeating: Array(repeating: 0, count: n + 1 ) , count: m + 1) // Following steps build L[m+1][n+1] in bottom up fashion. Note // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in stride(from: 0, through: m, by: 1) { for j in stride(from: 0, through: n, by: 1) { if i == 0 || j == 0 { L[i][j] = 0; } else if X[X.index( X.startIndex , offsetBy: (i - 1) )] == Y[Y.index( Y.startIndex , offsetBy: (j - 1) )] { L[i][j] = L[i-1][j-1] + 1 } else { L[i][j] = max(L[i-1][j], L[i][j-1]) } } } // Following code is used to print LCS var index = L[m][n] // Create a character array to store the lcs string var lcs = "" // Start from the right-most-bottom-most corner and // one by one store characters in lcs[] var i = m var j = n while (i > 0 && j > 0) { // If current character in X[] and Y are same, then // current character is part of LCS if X[X.index( X.startIndex , offsetBy: (i - 1) )] == Y[Y.index( Y.startIndex , offsetBy: (j - 1) )] { lcs.append(X[X.index( X.startIndex , offsetBy: (i - 1) )]) i-=1 j-=1 index-=1 } // If not same, then find the larger of two and // go in the direction of larger value else if (L[i-1][j] > L[i][j-1]) { i-=1 } else { j-=1 } } // return the lcs return String(lcs.characters.reversed()) } // Returns length of LCS for X[0..m-1], Y[0..n-1] private static func lcSubstring(_ X : String , _ Y : String ) -> String { let m = X.characters.count let n = Y.characters.count var L = Array(repeating: Array(repeating: 0, count: n + 1 ) , count: m + 1) var result : (length : Int, iEnd : Int, jEnd : Int) = (0,0,0) // Following steps build L[m+1][n+1] in bottom up fashion. Note // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in stride(from: 0, through: m, by: 1) { for j in stride(from: 0, through: n, by: 1) { if i == 0 || j == 0 { L[i][j] = 0; } else if X[X.index( X.startIndex , offsetBy: (i - 1) )] == Y[Y.index( Y.startIndex , offsetBy: (j - 1) )] { L[i][j] = L[i-1][j-1] + 1 if result.0 < L[i][j] { result.length = L[i][j] result.iEnd = i result.jEnd = j } } else { L[i][j] = 0 //max(L[i-1][j], L[i][j-1]) } } } // Following code is used to print LCS let lcs = X.substring(with: X.index(X.startIndex, offsetBy: result.iEnd-result.length)..<X.index(X.startIndex, offsetBy: result.iEnd)) // return the lcs return lcs } // driver program class func subsequenceOf(_ strings : [String] ) -> String { var answer = strings[0] // For on string answer is itself for i in stride(from: 1, to: strings.count, by: 1) { answer = lcSubsequence(answer,strings[i]) } return answer } class func substringOf(_ strings : [String] ) -> String { var answer = strings[0] // For on string answer is itself for i in stride(from: 1, to: strings.count, by: 1) { answer = lcSubstring(answer,strings[i]) } return answer } } Usage : let strings = ["ON/OFF office lights", "DIM office lights", "VALUE office lights", "FB office lights", "FB VALUE office lights"] print(LongestCommon.subsequenceOf(strings)) print(LongestCommon.substringOf(strings))
Optimizing Performance for Level Generation
I'm generating simple game maps using a method described in this post. I'm using the second method of starting with a seed tile and randomly growing out. I'm testing it in a Swift playground on a 30x30 array. The problem is my method takes several minutes to generate a 30x30 map, and maps in my real game might exceed 100x100 tiles. How can I optimize the following code to run faster? import UIKit import SpriteKit var map = [[String]](count: 30, repeatedValue:[String](count: 30, repeatedValue:" ")) var landTiles = [(y: Int,x: Int)]() landTiles.append((15,x: 15)) let minX = 3 let maxX = 28 let minY = 3 let maxY = 28 var coastTiles = [(y: Int,x: Int)]() var hasReachedBounds = false while !hasReachedBounds { coastTiles = [] for tile in landTiles { let coastal = isCoastal(tile.y, x: tile.x) if coastal { coastTiles.append(tile) } } let numTiles = UInt32(coastTiles.count) print(map) let randomTile = coastTiles[Int(arc4random_uniform(numTiles))] if randomTile.x <= minX || randomTile.x >= maxX || randomTile.y <= minY || randomTile.y >= maxY { hasReachedBounds = true break } let coastal = isCoastal(randomTile.y, x: randomTile.x) if !coastal{ continue } let randomPosition = arc4random_uniform(4) + 1 switch randomPosition { case 1: landTiles.append((randomTile.y + 1, randomTile.x)) map [randomTile.y + 1][randomTile.x] = "&" case 2: landTiles.append((randomTile.y, randomTile.x + 1)) map [randomTile.y][randomTile.x + 1] = "&" case 3: landTiles.append((randomTile.y - 1, randomTile.x)) map [randomTile.y - 1][randomTile.x] = "&" case 4: landTiles.append((randomTile.y, randomTile.x - 1)) map [randomTile.y][randomTile.x - 1] = "&" default: break } } func isCoastal (y: Int, x: Int) -> Bool{ if map[y + 1][x] == " " || map[y][x + 1] == " " || map[y - 1][x] == " " || map[y][x - 1] == " "{ return true } else { return false } } print(map)
ActionScript Unexpected Slashes, Parenthesis, and Squiggly-brackets?
This ActionScript code I have been working on for a few days now works 100% just fine in JavaScript, but when I try to compile it in ActionScript it says I have unexpected /, ), and } symbols. Is this syntax wrong and if so how should I fix it? I figured I could test it as Javascript for quicker testing using http://jsfiddle.net/ but now I'm like =( var txt = "This is a [rainbow]test to show that I can[/rainbow] make whatever I want [rainbow]appear as a rainbow[/rainbow] because I am [rainbow]awesome[/rainbow]."; if ((txt.indexOf("[rainbow]") > -1) && (txt.indexOf("[/rainbow]") > -1)) { var colors = ['f0f', 'f0c', 'f09', 'f06', 'f03', 'f00', 'f30', 'f60', 'f90', 'fc0', 'ff0', 'cf0', '9f0', '6f0', '3f0', '0f0', '0f3', '0f6', '0f9', '0fc', '0ff', '0cf', '09f', '06f', '03f', '00f', '30f', '60f', '90f', 'c0f']; function rainbowify(text) { return text.replace(/\[rainbow\](.+?)\[\/rainbow\]/g, function(_, inner) { return inner.replace(/./g, function(ch, i) { return '<font color="#' + colors[i % colors.length] + '">' + ch + '</font>'; }); }) } txt = rainbowify(txt); document.write(txt); }
Well, this is it: txt = txt.replace("'", "#"); if ((txt.indexOf("[rainbow]") > -1) && (txt.indexOf("[/rainbow]") > -1)) { var firstChar = txt.indexOf("[rainbow]") + 9; var lastChar = txt.indexOf("[/rainbow]"); while (lastChar <= txt.lastIndexOf("[/rainbow]")) { var RAINBOWTEXT = ''; var i = firstChar; while (i < lastChar) { RAINBOWTEXT += txt.charAt(i); i++ } var text = RAINBOWTEXT; var texty = ''; colors = new Array('ff00ff','ff00cc','ff0099','ff0066','ff0033','ff0000','ff3300','ff6600','ff9900','ffcc00','ffff00','ccff00','99ff00','66ff00','33ff00','00ff00','00ff33','00ff66','00ff99','00ffcc','00ffff','00ccff','0099ff','0066ff','0033ff','0000ff','3300ff','6600ff','9900ff','cc00ff'); i = 0; while (i <= text.length) { var t = text.charAt(i); if (t != undefined) { texty += "<font color=\"#" + colors[i % colors.length] + "\">" + t + "</font>"; i++; } } texty = texty.replace("> <", "> <"); var REPLACEME = "[rainbow]" + RAINBOWTEXT + "[/rainbow]"; txt = txt.replace(REPLACEME, texty); if (lastChar == txt.lastIndexOf("[/rainbow]")) { break; } nextChar = lastChar + 10; firstChar = txt.indexOf("[rainbow]", lastChar) + 9; lastChar = txt.indexOf("[/rainbow]", lastChar); } } txt = txt.replace("#", "'");