Assigning mice to holes in swift
Swift program for Assigning mice to holes. Here more information.
import Foundation
/*
Swift 4 program for
Assign mice to holes
*/
class Deliver
{
func absValue(_ x: Int) -> Int
{
if (x < 0)
{
return -x;
}
return x;
}
func assignHole(_ mices: [Int],
_ holes: [Int],
_ n: Int,
_ m: Int)
{
if (n != m)
{
// When mice and holes are not equal
return;
}
var result: Int = 0;
// Sort given data
let ho = holes.sorted();
let mi = mices.sorted();
var i: Int = 0;
// Find max absolute distance
while (i < n)
{
if (result < self.absValue(mi[i] - ho[i]))
{
result = self.absValue(mi[i] - ho[i]);
}
i += 1;
}
print(result);
}
static func main(_ args: [String])
{
let task: Deliver = Deliver();
// Position of mice
let mices: [Int] = [-3, 7, 5, 9, 16];
// Position of holes
let holes: [Int] = [1, 9, 15, 4, 14];
// Get the length
let n: Int = mices.count;
let m: Int = holes.count;
/*
-3 -2 -1 0 1 4 9 14 15
─────────────────☉─────☉──────────☉─────────☉──☉─────
♉ ♉ ♉ ♉ ♉
-3 5 7 9 16
Mics position
---------------------------------------------------
Step ➀ position -3 Mice are enter in nearest holes
-3 -2 -1 0 1 4 9 14 15
─────────────────☉─────☉──────────☉─────────☉──☉─────
♉ - - - ┘ ♉ ♉ ♉ ♉
-3 ← Mics position
Time to move : 4
---------------------------------------------------
Step ➁ position 5 Mice are enter in nearest holes 4
-3 -2 -1 0 1 4 9 14 15
───────────────────────☉──────────☉─────────☉──☉─────
└ ♉ ♉ ♉ ♉
5 ← Mics position
Time to move : 1
---------------------------------------------------
mice ➂ position 7 are enter in nearest holes 9
-3 -2 -1 0 1 4 9 14 15
──────────────────────────────────☉─────────☉──☉─────
♉ - ┘ ♉
♉
7 ← Mics position
Time to move : 2
---------------------------------------------------
mice ➃ position 9 are enter in nearest holes 14
-3 -2 -1 0 1 4 9 14 15
────────────────────────────────────────────☉───☉─────
♉ -- - - ┘ ♉
9 ← Mics position
Time to move : 5
--------------------------------------------------
mice ➄ position 16 are enter in nearest holes 15
-3 -2 -1 0 1 4 9 14 15
───────────────────────────────────────────────☉─────
└ ♉
Mics position->16
Time to move : 1
----------------------------------------------------
Result = 5
*/
task.assignHole(mices, holes, n, m);
}
}
Deliver.main([String]());
Output
5
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment