Copy value of the previous array for preceding 0 in swift 4 - swift3

In swift I have an array like this:
var array = [ 70, 75, 0, 0, 0, 87, 90, 85, 0]
What I want to do is when the value is 0 it will copy the previous first value which is not equal to 0. So the output will become:
[ 70, 75,75, 75, 75, 87, 90, 85, 85]
I’ve tried this code below:
func fillingEmpValues(dataArray:[Int]) -> [Int?] {
var newValue = [Int]()
var array = dataArray
for (index, var element) in array.reversed().enumerated() {
if (element == 0) { // if element is 0
if(index != 0) { // if the index is not 0 proceed
array[index] = (dataArray.reversed()[index-1])
}
}
}
return newValue
}
But the codes above is not working as I expected the output is still the same. What am i MISSING? Thanks

Your code does not work because nothing is appended to newValue. Please notice the yellow warnings.
My suggestion uses a temporary variable (temp).
In the loop
if the value != 0 the value is appended and the temporary variable is set to the value.
if the value == 0 the temporary variable is appended.
func fillingEmpValues(dataArray:[Int]) -> [Int] {
var newValue = [Int]()
var temp = 0
for element in dataArray {
if element != 0 {
newValue.append(element)
temp = element
} else {
newValue.append(temp)
}
}
return newValue
}
let array = [ 70, 75, 0, 0, 0, 87, 90, 85, 0]
let filledArray = fillingEmpValues(dataArray: array) // [70, 75, 75, 75, 75, 87, 90, 85, 85]
Note: Why is your return value [Int?]? Optionals are not involved at all.
Edit:
The other condition in the comments can be accomplished with
func fillingEmpValues(dataArray:[Int]) -> [Int] {
var newValue = [Int]()
var temp = dataArray.first{ $0 != 0 } ?? 0
for (index, element) in dataArray.enumerated() {
if element != 0 {
newValue.append(element)
} else {
temp = dataArray.dropFirst(index).first{ $0 != 0 } ?? temp
newValue.append(temp)
}
}
return newValue
}
let array = [ 0, 0, 83, 0, 0, 87, 90, 85, 0]
let filledArray = fillingEmpValues(dataArray: array) // [83, 83, 83, 87, 87, 87, 90, 85, 85]

I might suggest using reduce(into:):
let array = [70, 75, 0, 0, 0, 87, 90, 85, 0]
let array2 = array.reduce(into: [Int]()) { (result, value) in
if value == 0 {
result.append(result.last ?? 0)
} else {
result.append(value)
}
}
Yielding:
[70, 75, 75, 75, 75, 87, 90, 85, 85]

Related

Convert Solana public key from UINT8Array

I have generated accounts using the Solana CLI, but I am getting the public and private keys as
publicKey: Uint8Array(32) [
102, 255, 46, 44, 90, 176, 207, 98,
251, 66, 136, 190, 240, 59, 198, 177,
169, 35, 153, 3, 163, 68, 188, 214,
225, 46, 55, 111, 159, 157, 182, 111
],
but I want readable format to sustain key for next transaction.
You can try this
console.log(wallet.publicKey.toBase58());
Pubkey is base58 so this (dirty) vanilla (or any base58 lib) should work.
// ref: https://gist.github.com/diafygi/90a3e80ca1c2793220e5/
const MAP = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const encode = function (B) { const A = MAP; var d = [], s = "", i, j, c, n; for (i in B) { j = 0, c = B[i]; s += c || s.length ^ i ? "" : 1; while (j in d || c) { n = d[j]; n = n ? n * 256 + c : c; c = n / 58 | 0; d[j] = n % 58; j++ } } while (j--) s += A[d[j]]; return s };
const decode = function (S) { const A = MAP; var d = [], b = [], i, j, c, n; for (i in S) { j = 0, c = A.indexOf(S[i]); if (c < 0) return undefined; c || b.length ^ i ? i : b.push(0); while (j in d || c) { n = d[j]; n = n ? n * 58 + c : c; c = n >> 8; d[j] = n % 256; j++ } } while (j--) b.push(d[j]); return new Uint8Array(b) };
encode(new Uint8Array([
102, 255, 46, 44, 90, 176, 207, 98,
251, 66, 136, 190, 240, 59, 198, 177,
169, 35, 153, 3, 163, 68, 188, 214,
225, 46, 55, 111, 159, 157, 182, 111
]))
Output
7w4GYV1BxE9Vvn93BG3NZzZQAYoiTXWnNX8rdXBgQ5Tt

Pass a list to a get call Rest-Assured

I want to list the user's comment. I have gotten the list of post ids, I think of passing the ids of the post to the comments. I passed the id list to the comment url as below. When I did so it returned empty array -
[]
[
]
[]
post idList = [81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
Pass list to a get command in RestAssured:
public static void searchForUserCommentinnPost( ) throws Throwable {
RequestSpecification httpRequest = given();
httpRequest.header("Content-Type", "application/json");
Response response = httpRequest.get("https://jsonplaceholder.typicode.com/comments?postId=" +idList);
// Get Response Body
ResponseBody body = response.getBody();
String bodyStringValue = body.asString();
System.out.println(bodyStringValue);
response.prettyPrint();
}
You can pass the list of query params like this:
#Test
void name() {
List<Integer> postIds = Arrays.asList(81, 82, 83, 84, 85, 86, 87, 88, 89, 90);
Response res = RestAssured.given().queryParam("postId", postIds)
.get("https://jsonplaceholder.typicode.com/comments");
List<String> contents = res.jsonPath().getList("body");
contents.forEach(System.out::println);
}
This is the result:

How to use this type of array,struct

I have to do an exercise in C++ and I have a this kind of array-structure and I have never seen it before and I don't know how to use it, if someone can explain me please.
struct Fighter{
string type; // TIE Fighter, X-Wing, ...
int velocity;
int attack; // attack power
int shield; // current shield status.
int cost; // cost in credits};
const Fighter FIGHTERTABLE[] = {
{ "TIE-Fighter", 150, 75, 30, 45 },
{ "TIE-Bomber", 80, 150, 45, 75 },
{ "TIE-Interceptor", 180, 65, 30, 55 },
{ "TIE-Advanced", 160, 80, 90, 95 },
{ "X-Wing", 175, 90, 75, 65 },
{ "Y-Wing", 90, 150, 90, 90 },
{ "A-Wing", 200, 60, 50, 45 },
{ "B-Wing", 120, 200, 90, 100 }
};
const string FIGHTERABR[]= { "tf", "tb", "ti", "ta",
"xw", "yw", "aw", "bw"
};
What you have is an initialized array of structure 'Fighter',
as to how would you use it or access values?
it will be same as normal array
i.e.
string type = FIGHTERTABLE[0].type // type will be equal to "TIE-Fighter"
type = FIGHTERTABLE[0].type // now type will be equal to "TIE-Bomber"
exactly like a normal array, hope this clears things a bit.
It is an array of the type Fighter. So each element is a Fighter and is initialized using an initializer list {std::string,int,int,int,int}.
Read more about initializer-list

Compare tuple values in Two lists

**for i in range(a):
p=int(raw_input("Enter Elements in List1:"))
list1.append(p)
d1=defaultdict(int)
for item in list1:
d1[item]+=1
print list1
print d1.items()
print ""**
How to compare tuple values in the following list output?
Here my answer should return the tuple values (207,2), (208,1) and (209,1) because those are same in both the lists.
input1 : [203, 203, 204, 204, 205, 206, 207, 208, 207, 209]
output1: [(203, 2), (204, 2), (205, 1), (206, 1), (207, 2), (208, 1), (209, 1)]
input2: [204, 203, 205, 205, 206, 206, 207, 207, 208, 209, 205, 206, 205]
output2: [(203, 1), (204, 1), (205, 4), (206, 3), (207, 2), (208, 1), (209, 1)]
You can use Counter
>>> from collections import Counter
>>> lst = [203, 203, 204, 204, 205, 206, 207, 208, 207, 209]
>>> freqs = Counter(lst)
>>> freqs
Counter({203: 2, 204: 2, 207: 2, 205: 1, 206: 1, 208: 1, 209: 1})
>>> lst2 = [204, 203, 205, 205, 206, 206, 207, 207, 208, 209, 205, 206, 205]
>>> Counter(lst2)
Counter({205: 4, 206: 3, 207: 2, 203: 1, 204: 1, 208: 1, 209: 1})
First compare method:
>>> [ k for k,v in Counter(lst2).iteritems() if v == Counter(lst)[k] ]
[207, 208, 209]
Second compare method:
>>> for k,v in Counter(lst2).iteritems():
... if v == Counter(lst)[k]:
... print k
...
207
208
209

groovy sublist removal

I have a list:
def clc = [[1, 15, 30, 42, 48, 100], [58, 99], [16, 61, 85, 96, 98], [2, 63, 84, 90, 91, 97], [16, 61, 85, 96], [23, 54, 65, 95], [16, 29, 83, 94], [0, 31, 42, 93], [33, 40, 51, 56, 61, 62, 64, 89, 92], [0, 63, 84, 90, 91]]
and a sublist
def subclc = [[1, 15, 30, 42, 48, 100], [58, 99], [16, 61, 85, 96, 98], [2, 63, 84, 90, 91, 97]]
I need to remove sublist from original list
I do so:
subclc.each{
clc.remove(it)
}
but it throws an exceprion Exception in thread "main" java.util.ConcurrentModificationException
I do not understand where is problem and how to solve the problem
Short answers:
For more groovyness and immutability, preserving the original list:
def removed = clc - subclc
assert removed == [[16, 61, 85, 96], [23, 54, 65, 95], [16, 29, 83, 94], [0, 31, 42, 93], [33, 40, 51, 56, 61, 62, 64, 89, 92], [0, 63, 84, 90, 91]]
And the java way, changing the original list:
clc.removeAll subclc
assert clc == [[16, 61, 85, 96], [23, 54, 65, 95], [16, 29, 83, 94], [0, 31, 42, 93], [33, 40, 51, 56, 61, 62, 64, 89, 92], [0, 63, 84, 90, 91]]
Long answer:
You are Iterator-ing through a list while changing the list. In this case you are better using Iterator.remove(), which is being abstracted by the foreach loop.
When you change the list using the foreach loop, you bump into the iterator checks for modification using checkForComodification(). Getting the iterator explicitly works:
list1 = [10,20,30,40,50,60,70,80,90]
list2 = [50,60,80]
def iter = list1.iterator()
while (iter.hasNext()) {
def item = iter.next()
if (list2.contains(item)) iter.remove()
}
assert list1 == [10,20,30,40,70,90]
Or you can use indexes. Note you need to control the index:
list1 = [10,20,30,40,50,60,70,80,90]
list2 = [50,60,80]
for (int i = 0; i < list1.size(); i++) {
def item = list1[i]
if (list2.contains(item)) { list1.remove i-- }
}
assert list1 == [10,20,30,40,70,90]