Write a function index -- takes list and a number, and returns the index of the first element with the specified value - insert

Wouldn't this question need 3 parameters instead of 2, being the list, index, and item being added?

You don't tell us what language you're working in but your function will have 2 parameters: the list and the value looked for, and 1 return type. If it is Java it might be:
public static int findIndex(String[] myList, String valueToLookFor) {
int indice;
// calculations here
return indice;
}
I believe in some languages you can speak if IN parameters and OUT parameters in which case yes, there are 2 IN parameters plus 1 OUT parameter = 3.

Related

Does GraphQL take Int as enum

I was trying to create an enum type with Int value in GraphQL schema but failed. I might miss something in the doc. Anyone has any idea about how to implement Int value in the enum type like below?
enum IntValue {
1
2
3
}
You could declare something like
enum IntValue { _1 _2 _3 }
enum IntName { ONE TWO THREE }
but in both cases those enumerated values would be different from the numbers 1, 2, 3.
You can't declare something that looks like an enum but contains actual numbers. In the specification, an EnumTypeDefinition contains a list of EnumValueDefinition, each of which contains a single EnumValue; each value is
Name but not true or false or null
and finally a Name must begin with an underscore or a ASCII letter.

Linq statement involving index based update of value not working

In my C# winforms project, I wanted to update a specific index based position in a collection (named List l1 here).
I tried below code:
l1.Where((s, i1) => i1 == intvalue).Select(s => { if (s > 0) s = -1; return s; };
I wanted to set value at invalue index to -1 in the list l1, but when I do so with above statement the value in l1 is not changed. Please help! I am new to Linq and have searched the topic 'index based change of value in a collection' everywhere, but can't resolve my problem as it involves BigInteger type and I have so many elements in the list that their total count passes the allowed max value for int type in c#. So when I type l1[intvalue] it says can't convert BigInteger to int for index position.
Thanks
LINQ is Language INtegrated Queries. It's purpose is querying data. If you want to modify list item:
if (l1[intvalue] > 0)
l1[intvalue] = -1;
Also I'd like to explain why your query is not changing list.
On first step you are selecting list items by some condition. Very strange condition by the way. If you want to select item by index, there is operator ElementAt.
Then you are doing projection. I.e. you are calling anonymous method which accepts each selected item and produce some result. Each item passed to that method as s argument. And when you are assigning -1 to s you are actually assigning value to method argument. That does not affect items in the list. Even if your list will contain items of reference type instead of integers, assigning value to method argument will just change where argument variable points. It will not change references in original list. Though you still can modify items of reference type. But such side-effects in projection methods are not good practice.

How to return-7-6-5-4-3-2-1012345678910111213

Code below is in Objective C in Xcode. I am trying to return -7-6-5-4-3-2-1012345678910111213 as the method is expecting that response. number = -7 and otherNumber = 13 How do I return the series of numbers? I tried the method below but with no success...
while (number < otherNumber) {
++number;
return number;
}
Another thing to look out for is how your parameters are getting passed in to the method. Since we dont know if "number" is always going to be less than "otherNumber" you should check to find out which of the two numbers being passed in is lower before using them in your while loop.
this is very similar to the previous post but it might make it a tad clearer:
//find which number is low and which is high and set it accordingly
while (low <= high){
//then append low to end of string
++low;
}
//return your string
And this handles the case when the numbers are equal
In Objective-C, methods can only have one return value.
If your method returns an array, something like this would work:
// Create an NSMutableArray
while (number < otherNumber) {
// Add the number to the array
++number;
}
// Return the array
Or, similarly, if your method returns a string:
// Create an NSMutableString
while (number < otherNumber) {
// Append the number to the end of the string
++number;
}
// Return the string
A few notes:
your conditional, number < otherNumber, won't capture the case where number == otherNumber. Since in your example otherNumber is 13, and you want that included, you may want to use number <= otherNumber.
you can only compare scalar numbers (like NSInteger or CGFloat) with the inequality operators (like < and >). However, you can only add objects to NSMutableArray and NSMutableString. So you'll need to convert between the scalar numbers and NSNumber as appropriate.
Since it looks like you're learning Objective-C, note that this is different from Swift, which does allow methods to return multiple values.

Linq how parameters are passed in select

I am learning LINQ and I found this example.
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
Console.WriteLine("Number: In-place?");
foreach (var n in numsInPlace)
{
Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}
I don't understand execution of the below line:
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
As per my understanding num and index are parameters, but I don't understand where we decide that first parameter will be a number and second parameter will be index of the number?
Is it something that is fixed for int type of arrays?
Can anybody please help me understanding this?
Thanks in advance.
The definition of method Select decides it.
There are at lest 2 definitions for Select and one says it takes Func<MyInput,int,MyReturn>. We know that all but the last generic parameter of Func are inputs, and the last one is output.
Func is a special type of object (type of delegate) that has a method called Invoke() to run it and a special syntax-sugar - shorthand () which says that you can omit the Invoke and just write ().
Func<object, int> d = x => 1
d.Invoke(null) // will always return 1
d(new Object()) // also the same
So compiler takes your function and tries to find one of Selects that can accept this kind of function. Then it compiles. And then in run-time the Select just takes first, second etc. element from collection and runs your function by passing the element (and the index if the overload of Select with the function that accepts index has been chosen).
(num, index, TResult) => new { .... } is an anonymous function of type Func delegate.
It is defined by .Net Framework. Thus the First parameter is an object, where as second parameter is index of an object in an array.
Func<T, Index, TResult> Delegate
Func translated to English is: “A method that takes an T and Index of T in an array, and returns a TResult.
There is another thing called Action delegate, where there is no return.
Please have a reference to this link:
http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/
See this link.
The first argument to selector represents the element to process. The second argument to selector represents the zero-based index of that element in the source sequence. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements.

LINQ and CASE Sensitivity

I have this LINQ Query:
TempRecordList = new ArrayList(TempRecordList.Cast<string>().OrderBy(s => s.Substring(9, 30)).ToArray());
It works great and performs sorting in a way that's accurate but a little different from what I want. Among the the result of the query I see something like this:
Palm-Bouter, Peter
Palmer-Johnson, Sean
Whereas what I really need is to have names sorted like this:
Palmer-Johnson, Sean
Palm-Bouter, Peter
Basically I want the '-' character to be treated as being lower than the character so that names that contain it show up later in an ascending search.
Here is another example. I get:
Dias, Reginald
DiBlackley, Anton
Instead of:
DiBlackley, Anton
Dias, Reginald
As you can see, again, the order is switched due to how the uppercase letter 'B' is treated.
So my question is, what do I need to change in my LINQ query to make it return results in the order I specified. Any feedback would be greatly appreaciated.
By the way, I tried using s.Substring(9, 30).ToLower() but that didn't help.
Thank you!
To customize the sorting order you will need to create a comparer class that implements IComparer<string> interface. The OrderBy() method takes comparer as second parameter.
internal sealed class NameComparer : IComparer<string> {
private static readonly NameComparer DefaultInstance = new NameComparer();
static NameComparer() { }
private NameComparer() { }
public static NameComparer Default {
get { return DefaultInstance; }
}
public int Compare(string x, string y) {
int length = Math.Min(x.Length, y.Length);
for (int i = 0; i < length; ++i) {
if (x[i] == y[i]) continue;
if (x[i] == '-') return 1;
if (y[i] == '-') return -1;
return x[i].CompareTo(y[i]);
}
return x.Length - y.Length;
}
}
This works at least with the following test cases:
var names = new[] {
"Palmer-Johnson, Sean",
"Palm-Bouter, Peter",
"Dias, Reginald",
"DiBlackley, Anton",
};
var sorted = names.OrderBy(name => name, NameComparer.Default).ToList();
// sorted:
// [0]: "DiBlackley, Anton"
// [1]: "Dias, Reginald"
// [2]: "Palmer-Johnson, Sean"
// [3]: "Palm-Bouter, Peter"
As already mentioned, the OrderBy() method takes a comparer as a second parameter.
For strings, you don't necessarily have to implement an IComparer<string>. You might be fine with System.StringComparer.CurrentCulture (or one of the others in System.StringComparer).
In your exact case, however, there is no built-in comparer which will handle also the - after letter sort order.
OrderBy() returns results in ascending order.
e comes before h, thus the first result (remember you're comparing on a substring that starts with the character in the 9th position...not the beginning of the string) and i comes before y, thus the second. Case sensitivity has nothing to do with it.
If you want results in descending order, you should use OrderByDescending():
TempRecordList.Cast<string>
.OrderByDescending(s => s.Substring(9, 30)).ToArray());
You might want to just implement a custom IComparer object that will give a custom priority to special, upper-case and lower-case characters.
http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx

Resources