Java8 - how to determine if each element in a sorted list is one less that previous? [closed] - list

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed yesterday.
Improve this question
I have a list of ints that is sorted in order of highest > lowest:
I want to determine if each list element is one less than the previous, how can I do so, ideally using streams?
This would pass:
10
9
8
7
This would fail:
10
8
7
6

You can use IntStream to process the list sequentially and compare the previous index value if it is one more than the current one
public static void main(String[] args) {
List<Integer> sequentList = Arrays.asList(10, 9, 8, 7);
List<Integer> nonSequentList = Arrays.asList(10, 8, 7, 6);
System.out.println(isInSequence(sequentList));
System.out.println(isInSequence(nonSequentList));
}
private static boolean isInSequence(List<Integer> sequentList) {
return IntStream.range(1, sequentList.size())
.allMatch(i -> (sequentList.get(i - 1) - sequentList.get(i)) == 1);
}

There are multiple solutions to solve the problem, streams are hardly the ideal one in this case, both in terms of efficiency or readability:
Using streams:
One example could be:
private boolean isContiguousListWithStreams(List<Integer> sortedDescInput) {
return IntStream.range(1, sortedDescInput.size())
.noneMatch(i -> sortedDescInput.get(i - 1) - sortedDescInput.get(i) != 1);
}
Using For loop:
In this simple scenario, streams might just answer it as readable and efficient, but just to point out that in many complex scenarios, a simple for loop can be just what's needed and it can be as efficient and readable (if not more).
private boolean isContiguousListWithLoop(List<Integer> sortedDescInput) {
for (int i = 1; i < sortedDescInput.size(); i++) {
if (sortedDescInput.get(i - 1) - sortedDescInput.get(i) != 1) {
return false;
}
}
return true;
}
Using neither:
Since it was established that the input list is sorted in descending order, neither streams nor for loops are actually needed, a simple first - last + 1 == length formula will do:
private boolean isContiguousList(List<Integer> sortedDescInput) {
return sortedDescInput.size() < 2
|| sortedDescInput.get(0) - sortedDescInput.get(sortedDescInput.size() - 1) + 1 == sortedDescInput.size();
}
Please note that the efficiency of any of these solutions will depend on the underlying implementation of the list (e.g. Array lists are efficient to access based on an index, unlike linked lists).

Related

Checking equality/inequality of multiple variables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's say we have four variables: int a, b, c, d;. I need to check if excatly two of them are equal.
So for example: 1 1 9 5 is true, but 3 9 8 4 and 3 3 3 1 are false.
Of course writing an if statement for this would take a lot of time, won't be easily readable and it would be easy to make a mistake writing it.
What is the best way to write such statement?
There are several ways to do this.
One involves explicitly checking all the conditions. Since you have 4 variables, you only 6 conditions to check. These can easily be counted.
int n = (a == b) + (a == c) + (a == d) + (b == c) + (b == d) + (c == d);
Then check if n is 1. This works because a boolean value will be converted into an int (value 1 for true, 0 for false).
Another possibility is to store them all in a container (like a vector), sort it, then count the number of adjacent identical values.

use of: index & 0x01 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set.
index & 0x01
will be 1 if and only if index is odd.
If we have to deduce a general rule, we can say that for any non-negative number x,
x % y == (x & (y - 1))
provided that y is a positive power of 2.
This is a common hack in competitive coding. It is used because the competitive programmers think that bit-wise AND works faster than modulo.
In modern compilers, there is no performance difference at all. Read this thread.
There is no special reason in writing it as 0x01 instead of 1. Both compile to give the same assembly! Almost everyone (who uses this hack),= uses 1, because we have to type 3 characters extra in 0x01. :P
Here in this case, index & 0x1 is equivalent to index % 2 which is simply a condition to check if the number is odd. (Array indexes in C++ are always positive, unless you are going out of bound.)
As the other answers pointed out, while this is a well known pattern (see also this Q&A about that mask), it can be considered a premature optimization.
I'd like to suggest the following alternative to the posted code, which I find more readable. Your mileage may vary.
// Give a meaningful name.
constexpr auto is_odd = [] (auto x) -> bool {
return x % 2;
}
// Use it to simplify the condition.
if ( (arr[index] < 0) == is_odd(index) ) {
// Do something
}

How to implement this exercise (dynamic array)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm having like an assesment exercise.
So given a Number, for example 12345, I must find out the sum sequence of the digits of the given number (1 + 2 +3 + 4 +5) and then add to it the result (15), and repeat this till the sum sequence of the last number is a digit (in this case is 6).
Example : 12345 + 15 + 6 = 12366;
666 + 24 + 6 = 696;
I've been thinkig to store the digits in an array, but then I realized the array's size is static. Now I'm thinking to make a linked list, but I'm not really sure. Does it involve linked lists?
Just guide me to the right path. What should I use?
There's no magic needed here. Just do the obvious computation on integers:
int reduce(int n)
{
int result = 0;
while (n != 0) { result += n % 10; n /= 10; }
return result;
}
int your_problem(int n)
{
int result = n;
while (n >= 10) { n = reduce(n); result += n; }
return result;
}

if condition for a number multiple [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I got an if condition as a multiples of 5, i need to check if condition until a value <= 10000. My if statement looks like this
// in main function
if(value >=0 && value <16){
function(number,value);
}
else if(value >=5 && value <10){
value-=16;
function(number,value);
}
....
// function
int function(int n, int value){
return (n<<value)|(n>>(16-value))
}
Is there a better way to do this if statement. I am new to programming world and a bit curious to know how to do this.
Thanks in advance
You could use function pointers.
typedef void (*func)();
func fpointers[] = {func1, func2, func3}
int check = value / 5;
fpointers [check] ();
Put the amounts you're subtracting from value into an array, indexed by the multiple of 5 for each range:
int subtract[] = [2, 5, ...];
if (value > 0 && value < 5*(sizeof subtract/sizeof(*subtract))) {
value -= subtract[value/5];
functioncall(value);
}
If you need to evaluate the condition for multiples of 5 , I suggest you to use swich case
int check = value/5;
switch(check)
{
case 0: // 0 <= value < 5
// do things
break;
case 1 : // 5 <= value < 10
// do things ...
break;
.............
default:
break;
}
I got an if condition as a multiples of 5
To check if a number is a multiple of 5, use the modulus operator:
if (number % 5 == 0) ...
i need to check if condition until a value <= 10000
This sounds like you need a loop.

Translation of number into strings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to know whether there is a way in which we can print the number alphabetically i.e
123 should be printed as one two three.
The only condition is that we should not reverse the number and we should not use array.
I only know these two ways:
"Reverse the number", that is, taking the last digit and cutting it off. For each cut-off digit, one can use an array to look up the correct string.
using switch and a lot of cases
Any ideas?
for hundreds place:
int hundreds = my_num / 100 //Needs "/", NOT "%"
if(hundreds == 0)
cout << "zero";
else if(hundreds == 1)
cout << "one";
//repeat for 2-9
This process could be tweaked to do the other digits as well. It is also worth mentioning that the if/else block a) could be done with a switch/case if preferred, and b) could pretty easily be made into a separate function to avoid having to repeat the block of code over and over, I just wrote out as much as I did for clarity's sake. Note that this assumes the number you're "translating" is an integer. With integers the "/" operator will return the full quotient WITHOUT the remainder, e.g. 123 / 100 = 1, not 1.23
Not necessarily the easiest route, but you can make a function, say DigitToWord which will take a digit 0, 1, 2, ...etc to its word with a switch statement. Then I recommend using a for loop over the number, continuously dividing by 10 and taking the mod for the loop:
int num; //my number i want to print
int div = pow(10, (int)log10(num)); //find the largest power of 10 smaller than num
while(num > 0) {
int remainder = num%div;
int digit = num/div;
DigitToWord();
num = remainder;
}