Sorting NSMutableArray ascending (containing NSNumber) - nsarray

I tried to search for how to sort an nsmutablearray but I only got confused more- how can I sort an NSMutableArray containing 10 NSNumbers (may be null) ascending, like this-
NSMutableArray *a = [1,2,4,6,3,5,8,7,9,0]
to this- a = [0,1,2,3,4,5,6,7,8,9]
Thanks!

NSArray *array = #[ #1, #2, #4, #6, #3, #5, #8, #7, #9, #0 ];
array = [array sortedArrayUsingSelector:#selector(compare:)];

NSArray *a = #[#0,#1,#5,#2];
a = [a sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSNumber *)obj1 compare:obj2] == NSOrderedDescending;
}];
Mutable and word with [NSNull null]
NSMutableArray *a = [#[#1,#2,#4,#6,#3,#5,#8,#7,#9,#0,[NSNull null]] mutableCopy];
[a sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if (obj2 == [NSNull null]) {
return YES;
}
return [(NSNumber *)obj1 compare:obj2] == NSOrderedDescending;
}];

Related

writedump shows more than loop over a structure

My client wants a list of every item with the name of the categories it belongs to in each appropriate column.
<cfscript>
arr = ArrayNew(1);
arr[1] = '';
arr[2] = 'category B';
stc["Item One"] = arr;
arr[1] = 'category A';
arr[2] = '';
stc["Item Two"] = arr;
arr[1] = 'category A';
arr[2] = 'category B';
stc["Item Three"] = arr;
writedump(stc);
for (element in stc) {
WriteOutput(element & '<br>');
// The next line produces:
// Object of type class java.lang.String cannot be used as an array
for (i=1; i<=ArrayLen(element); i+=1) {
}
}
</cfscript>
Q: How do I get to the arrays inside of each element?
In your example, you are using a for ... in loop to iterate through the keys of the struct, not the values. This can be a bit confusing, for the same syntax with an array will iterate through the elements.
In your code, you have placed the key string into element, which isn't the array. This is the reason why the error Object of type class java.lang.String cannot be used as an array is produced.
As RRK has answered, to access the value in the struct you need to use the syntax struct[keyOfItem].
//Loop keys in the struct
for (key in stc) {
writeOutput(key & '<br>');
//Loop items in the array
for(element in stc[key]){
writeOutput(element & '<br>');
}
}
You can access the arrays inside using [] representation.
stc[element] This will get you the array.
for (i=1; i<=ArrayLen(stc[element]); i+=1) {
writedump(stc[element][i]);
}
DEMO

Make a new list from two other lists of different types by comparing values of each type

I have two Lists of objects that both implement an interface, but are otherwise unrelated. How can I create a new collection of objects containing only the objects of one of the lists that match a value in the other list?
Obviously I could use a for loop & do this manually, but I'd like to know how I can do this using Kotlin's standard library collection filtering functions.
So here's an example:
interface Ids
{
val id: Int
}
data class A(override val id: Int, val name: String) : Ids
data class B(override val id: Int, val timestamp: Long) : Ids
fun main(args: Array<String>) {
val a1 = A(1, "Steve")
val a2 = A(2, "Ed")
val aCol = listOf(a1, a2)
val b2 = B(2, 12345)
val b3 = B(3, 67890)
val bCol = listOf(b2, b3)
val matches = mutableListOf<B>()
// This is where I'm stuck.
// I want to filter bCol using objects from aCol as a filter.
// The result should be that matches contains only a single object: b2
// because bCol[0].id == aCol[1].id
// I'm guessing I need to start with something like this:
bCol.filterTo(matches) { ??? }
}
A straightforward approach would be to search aCol for an object with the same id for each b in bCol:
bCol.filter { b -> aCol.any { a -> a.id == b.id } }
However that may become too slow if your lists are big enough.
To make it more scalable you can first build a set of all ids in aCol:
val aColIds = aCol.map { it.id }.toSet()
And then use Set.contains method to determine whether b.id is in aColIds:
bCol.filter { it.id in aColIds }
// or equivalent
bCol.filter { aColIds.contains(it.id) }

issues when Iterate Map with list as value using groovy

def map = new HashMap<String,List<String>>()
def list = new ArrayList<String>()
def list1 = new ArrayList<String>()
list.add("hello1")
list​.add("world1")
list.add("sample1")
list.add("sample1")​​​​​​​​​​​​​​​​​​​​​​​​
list1.add("hello2")
list1.add("world2")
list1.add("sample2")
list1.add("sample2")
map.put("abc",list)
map.put("bcd",list1)
def data = new ArrayList<String>()
for(e in map){
println "key = ${e.key} value=${e.value}"
// data = "${e.value} as String[]"
data = "${e.value}"
println "size ${data.size()} " --(B)
check(data)
​}
def check(input)
{
println "${input.size()}" ---(A)
for(item in input){
print "$item "​​​​​​​​​​​​​​​​​}
​}​
I have to pass string[] to another java function from this groovy script. so I am trying to read the array list and then convert it into String array. But the problem is when I assign {e.value} to variable data and try to get the size data.size() (both step (A) and (B) ). and the size is 34. It is counting each character not the word as whole from the list. I want to iterate over each word from the list. Kindly let me know how to resolve this problem.
sample output is
key = abc value=[hello1, world1, sample1, sample1]
size 34
Here is the groovified vesion of creating the map and accessing it:
def map = [abc:['hello1', 'world1','sample1', 'sample1'], bcd:['hello2', 'world2','sample2', 'sample2']]
map.collect{ println "key: ${it.key}, list: ${it.value}, and size: ${it.value.size()}" }
Output:
key: abc, list: [hello1, world1, sample1, sample1], and size: 4
key: bcd, list: [hello2, world2, sample2, sample2], and size: 4
If you want to convert a list to an array you can just do it:
def list = ['hello1', 'world1','sample1', 'sample1']
assert list instanceof List
def array = list as String[]
assert array instanceof String[]
assert !(array instanceof List)

Create a new dynamically named list in groovy

I have a list of items that looks like this items = ["a", "b", "c"]
I also have a list of values that looks like this values = ["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3"]
my items list is static, but my values list will change often.
my code looks like this
for(z=0;z<items.size();z++){
for(i=0;i<values.size();i++){
if(values[i] =~ items[z]){
println value[i]
}
}
What I really want to do is add value[i] to a list with the name items[z], something that would function like ${"items[i]"} += value[i] and the code would read it as a += value[1], b += value[1] so on and so forth through my loops, so at the end I could do something like this
assert a == ["a1", "a2", "a3"]
assert b == ["b1", "b2"]
assert c == ["c1", "c2", "c3"]
Is it possible to do a dynamically named variable like this?
You can dynamically add variables but you will need to use this (being the instance of the object you are setting the variable on), e.g.:
this."${items[i]}" += value[i]
This should give you what you need or at least point you in the right direction.
As far as I undesrtand code should be like this:
def map = [:]
for(z=0;z<items.size();z++){
for(i=0;i<values.size();i++){
if(values[i] =~ items[z]){
if (map[values[i]] == null) {
map[values[i]] = []
}
map[values[i]].add(items[z])
}
}
}
assert map[values[0]] == ["a1", "a2", "a3"]
assert map[values[1]] == ["b1", "b2"]
assert map[values[2]] == ["c1", "c2", "c3"]
If you accept the fact that the output would be a Map, here is another approach based on each and findAll closures:
def items = ["a", "b", "c"]
def values = ["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3"]
def result = [:]
items.each{i->
result.put(i, values.findAll{v->v.startsWith(i)})
}
println result; //[a:[a1, a2, a3], b:[b1, b2], c:[c1, c2, c3]]
groupBy is your friend:
def groups = values.groupBy { v ->
items.find { i -> v =~ i }
}
assert groups.a == ['a1', 'a2', 'a3']
assert groups.b == ['b1', 'b2']
assert groups.c == ['c1', 'c2', 'c3']
As a sidenote I'd strongly recommend you give Groovy's excellent List/Map comprehension a thorough look; I can guarantee that once you get the idea, you'll no longer need to use for-loops in your code.

split List<User> in multiple List<User> in c#

I want to split List of user generic List into its small list with each 5 records.
Ex
I have List: u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15.
so must be split into
List1:u1,u2,u3,u4,u5
List2:u6,u7,u8,u9,u10
List3:u11,u12,u13,u14,u15
Any direct method available or need programing logic in c# ?
You can group on the index:
List<List<User>> lists =
list
.Select((u, i) => new { List = i / 5, User = u })
.GroupBy(g => g.List, g => g.User)
.Select(g => g.ToList())
.ToList();
You can also use Range to make a loop and get a part of the list for each iteration:
List<List<User>> lists =
Enumerable.Range(0, (list.Count + 4) / 5)
.Select(n => list.Skip(n * 5).Take(5).ToList())
.ToList();
You can Use Skip(count) and Take(count) methods.
// These are your objects, put here your init code
var list = Enumerable.Range(1, 20).ToList();
var lists = new List<int>[(list.Count + 4) / 5]; // The array of lists you wanted
for (int i = 0; i < lists.Length; i++)
{
lists[i] = list.Skip(i * 5).Take(5).ToList();
}
The (list.Count + 4) / 5 is a method to round UP the division (if I have 6 elements in list, I want two sublists)
If you really need a List of List...
var lists = new List<List<int>>((list.Count + 4) / 5);
for (int i = 0; i < lists.Capacity; i++)
{
lists.Add(list.Skip(i * 5).Take(5).ToList());
}
I think this might be more efficient since you're not doing groupings, orderings and such. This is just a single iteration over the dataset.
var splitList= new List<IEnumerable<User>>();
List<User> currentList = null;
int count = 0;
foreach(var user in users)
{
if (0 == count% 5)
{
currentList = new List<User>(5);
returnValue.Add(currentList);
}
currentList.Add(key);
count++;
}
return returnValue;