public static void get_sum_while (int[] num,int len)
{
int sum2,i=0;
while ( i<len)
{
sum2=sum2+num[i];
i++;
}
Console.WriteLine("The sum of the series by while loop is {0}",sum2);
}
public static int get_sum_recur (int[] num,int len)
{
int sum3;
if (len==0)
return sum3=sum3+num[0];
else
{
return sum3=num[len]+get_sum_recur(num,length-1);
}
}
}
Hello this gives sum of the series from three function the first two are okay but recursive did not give it give exception i don't where i go wrong and is it correct way to get sum by recursion?
The idea of summing a list by recursion is to sum the an element of the list with the sum of the same list without the chosen element.
sum([a,b,c,d,e]) = a + sum([b,c,d,e])
So the initial value of the result have to be set to 0.
Then choose an element, for example the first one, add it to the current result and call sum on the rest of the list with the new result.
When list is empty, end recursion.
In pseudo code, because I don't have a C# compiler, this gives :
public static int get_sum_recur(int result, int[] list) {
if (len(list)==0) {
return result; // end recursion
}
else {
return get_sum_recur(result+list[0], list[1:]);
}
}
public static main {
print(get_sum_recur(0, [1,2,3,4,5,6])
}
Related
Im trying to call this method from SDK
public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {
if (top < 0) {
throw new IllegalArgumentException("Top must be greater or equal to zero.");
}
if (left < 0) {
throw new IllegalArgumentException("Left must be greater or equal to zero.");
}
if (bottom < 1 || bottom <= top) {
throw new IllegalArgumentException("Bottom must be greater than zero and top.");
}
if (right < 1 || right <= left) {
throw new IllegalArgumentException("Right must be greater than zero and left.");
}
hasCrop = true;
cropTop = top;
cropLeft = left;
cropBottom = bottom;
cropRight = right;
return this;
}
How I can call the method if the parameters are from an Array or Map like this? Is that possible?
ArrayList arrayList = [299, 296, 301, 297]
crop(arraylist)
Java:
No you cant.
you will get this error:
Compilation Errors Detected
...
method crop in class Test cannot be applied to given types;
required: int,int,int,int
found: java.util.ArrayList<java.lang.Integer>
reason: actual and formal argument lists differ in length
Groovy:
Yes you can.
Check the sample code on groovyConsole.
def hello(int a, int b){
println "$a and $b"
}
hello(1, 2)
def param = [1,2]
hello(param)
public ThumborUrlBuilder crop(ArrayList params) {
if (params.size() != 4 ){
throw new IllegalArgumentException(...);
}
int top = params.get(0);
int left = params.get(1);
int bottom = params.get(2);
int right = params.get(3);
...
}
This is not directly possible in Java, because the function crop requires 4 parameters.
Passing the given ArrayList into the crop function would result in an error.
You could write your own function to handle the ArrayList for you like this:
public ThumboUrlBuilder special_crop(ArrayList arraylist){
crop(arraylist.get(0),arraylist.get(1),arraylist.get(2),arraylist.get(3));
}
I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly
Let's say I have a blocking method with is called List<UUID> listOf(int page).
If I want to paginate something like this, one idea is to do something like this:
public Observable<UUID> allOf(int initialPage) {
return fromCallable( () -> listOf(initialPage))
.concatWith( fromCallable( () -> allOf(initialPage + 1)))
.flatMap(x -> from(x));
}
If my service doesn't use the page number but the last element of the list to find next elements, how can I achieve it with RxJava?
I would still like to obtain the effect of doing something like allOf(0).take(20) and obtain, with concatWith, the call to the second Observable when the first one has completed.
But how can I do it when I need information from the previous call?
You could use a subject to send back the next page number to the beginning of a sequence:
List<Integer> service(int index) {
System.out.println("Reading " + index);
List<Integer> list = new ArrayList<>();
for (int i = index; i < index + 20; i++) {
list.add(i);
}
return list;
}
Flowable<List<Integer>> getPage(int index) {
FlowableProcessor<Integer> pager = UnicastProcessor.<Integer>create()
.toSerialized();
pager.onNext(index);
return pager.observeOn(Schedulers.trampoline(), true, 1)
.map(v -> {
List<Integer> list = service(v);
pager.onNext(list.get(list.size() - 1) + 1);
return list;
})
;
}
#Test
public void testPager() {
getPage(0).take(20)
.subscribe(System.out::println, Throwable::printStackTrace);
}
I'd like to know if two lists share values before applying an intersection. Something like bool DoIntersect(listA, listB) would be fabulous!
This is the code I came up with:
// Person is a class with Id and Name properties
List<Person> people1;
List<Person> people2;
// Populate people1 and people2...
// My current solution (pseudocode obviously)...
if (DoIntersect(people1, people2))
{
people1 = people1.Intersect(people2)
}
else
{
/* No shared people */
throw exception;
}
// Continue with the process...
It depends on exactly what you want:
// are there any common values between a and b?
public static bool SharesAnyValueWith<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return a.Intersect(b).Any();
}
For lists that don't overlap, this will iterate through a and b each once. For lists that overlap, this will iterate all the way through a, then through b until the first overlapping element is found.
// does a contain all of b? (ignores duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return !b.Except(a).Any();
}
This will iterate through a once, then will iterate through b, stopping on the first element in b not in a.
// does a contain all of b? (considers duplicates)
public static bool ContainsAllFrom<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
// get the count of each distinct element in a
var counts = a.GroupBy(t => t).ToDictionary(g => g.Key, g => g.Count());
foreach (var t in b) {
int count;
// if t isn't in a or has too few occurrences return false. Otherwise, reduce
// the count by 1
if (!counts.TryGetValue(t, out count) || count == 0) { return false; }
counts[t] = count - 1;
}
return true;
}
Similarly, this will iterate through a once, then will iterate through b, stopping on the first element in b not in a.
I believe without altering the fact that you're using a List you can't get better performance.
However, if you would have 2 sorted lists to begin with (requires overhead when creating them), then you could iterate through them with complexity of O(n) in order to find out if you have shared values.
Edit:
Although original OP doesn't have 2 sorted lists, in case someone will need it, here is the implementation for checking Intersection at O(n):
public Boolean DoIntersect(SortedList<int,String> listA,SortedList<int,String> listB )
{
if (listA == null || listA.Count == 0 || listB == null || listB.Count == 0)
{
return false;
}
var keysA = listA.Keys;
var keysB = listB.Keys;
int i = 0, j = 0;
while (i < listA.Count && j < listB.Count)
{
if (keysA[i] < keysB[j])
{
i++;
}else if (keysA[i] > keysB[j])
{
j++;
}
else
{
return true;
}
}
The above approach can be used also with IEnumerable lists, given that they are sorted, with slight variation - using GetEnumerator and iterating with it.
i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
try
{
//decimal find = decimal.Parse(txtnapsaserach.Text);
if (decimal.Parse(txtnapsaserach.Text) > 0)
{
List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();
}
}
catch (Exception Ex)
{
}
}
any solution for me . Because this works for me when i try to find string value.
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
float value;
if (!float.TryParse(txtnapsaserach.Text, out value))
return; // return if text cannot be parsed as float number
if (value > 0)
{
var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
napsaTableBindingSource.DataSource =
napsatabs.Where(p =>p.NapsaRate == value).ToList();
}
}
try this
i want to find value in List<> but i am not getting the integer value.
Your p.NapsaRate is either integer type or floating point number, (probably decimal) Convert your txtnapsaserach.Text to decimal value and then compare it in where clause.
decimal rate = 0;
if(!decimal.TryParse(txtnapsaserach.Text), out rate)
{
//Invalid number in textbox
}
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate == rate)).ToList();
if p.NapsaRate is of type double or float you can parse them accordingly using Double.TryParse or Double.Parse etc
The reason you are not getting any error is that you are using object.Equals method for comparing decimal value with string. You should always use == for equality comparison of value types.