How can I get Stream from 3 dimensional array in Java 8? - arrays

As I know to get Stream from 2 dimensional array but I want to know how I can get Stream from below 3 dimensional array?
int[][][] data = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
},
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
};

If you can do it with a two-dimensional array then doing it for N dimensional array is not that difficult.
The solution can be done as follows:
IntStream result = Arrays.stream(data)
.flatMap(Arrays::stream)
.flatMapToInt(Arrays::stream);
To better help understand what is going on above, you can split the method invocations as follows:
// the call to Arrays.stream yields a Stream<int[][]>
Stream<int[][]> result1 = Arrays.stream(data);
// the call to flatMap yields a Stream<int[]>
Stream<int[]> result2 = result1.flatMap(Arrays::stream);
// the call to flatMapToInt yields a IntStream
IntStream intStream = result2.flatMapToInt(Arrays::stream);

You just need to call flatMap another time to change the stream from int[][] to stream of int[].
IntStream stream = Arrays.stream(data)
.flatMap(twoDArray -> Arrays.stream(twoDArray))
.flatMapToInt(oneDArray -> Arrays.stream(oneDArray));

Related

Is there a way to print an entire array and not just printing the contents of the array by iterating through them?

In C, is there a way to print an entire array. For example print (in full) each row from a 2D array, NOT iterating through its contents and printing them independently? Below is an example of how I imagined the code would be:
int main() {
int Numbers[4][4] = {{5, 1, 1, 6},
{2, 2},
{3, 3, 3},
{4, 4, 4}};
for (int i=0; i<=3; i++){
printf("%i \n", Numbers[i]);
}
return 0;
}
I expect the output to be along the lines of:
{5, 1, 1, 6}
{2, 2}
{3, 3, 3}
{4, 4, 4}
However, when run the code I get the following output
-414054224
-414054208
-414054192
-414054176
No, there is no way to do what you are asking. You cannot do operations on whole arrays in C; you must iterate through and print each element separately. Array expressions in C lose their "array-ness" under most circumstances.

Count Pairs from two arrays with even sum

Problem Statement
Given two arrays A[] and B[] of N and M integers respectively. The task is to count the number of unordered pairs formed by choosing an element from array A[] and other from array B[] in such a way that their sum is an even number.
Note that an element will only be a part of a single pair.
Input: A[] = {9, 14, 6, 2, 11}, B[] = {8, 4, 7, 20}
Output: 4
{9, 7}, {14, 8}, {6, 4} and {2, 20} are the valid pairs.
Source
https://www.geeksforgeeks.org/count-pairs-from-two-arrays-with-even-sum/
My Problem
I am wondering how output doesn't have so many other pairs whose sum will be even i.e. {11,7}, {2,3} etc. and many others.
As you mentioned in the question, Element will only be a part of single pair
{11,7} and {2,3} are already considered in {9, 7} and {2, 20}.
It's given in the problem statement,
Note that an element will only be a part of a single pair.
That means 7 has already been paired in {9, 7} so you can't pair {11, 7}

How do you copy between arrays of different sizes in Rust?

If I have two arrays of different sizes:
let mut array1 = [0; 8];
let array2 = [1, 2, 3, 4];
How would I copy array2 into the first 4 bytes of array1? I can take a mutable 4 byte slice of array1, but I'm not sure how or if I can assign into it.
Manually one can do
for (dst, src) in array1.iter_mut().zip(&array2) {
*dst = *src
}
for a typical slice. However, there is a likely faster specialization in clone_from_slice:
dst[..4].clone_from_slice(&src)
A slightly older method is to use std::io::Write, which was implemented for &mut [u8].
use std::io::Write;
let _ = dst.write(&src)
This will write up to the end of dst and return how many values were written in a Result. If you use write_all, this will return an Err if not all bytes could be written.
The most flexible way is to use iterators to handle each element successively:
for (place, data) in array1.iter_mut().zip(array2.iter()) {
*place = *data
}
.mut_iter creates an Iterator that yields &mut u8, that is, mutable references pointing into the slice/array. iter does the same but with shared references. .zip takes two iterators and steps over them in lock-step, yielding the elements from both as a tuple (and stops as soon as either one stops).
If you need/want to do anything 'fancy' with the data before writing to place this is the approach to use.
However, the plain copying functionality is also provided as single methods,
.copy_from, used like array1.copy_from(array2).
std::slice::bytes::copy_memory, although you will need to trim the two arrays because copy_memory requires they are the same length:
use std::cmp;
use std::slice::bytes;
let len = cmp::min(array1.len(), array2.len());
bytes::copy_memory(array1.mut_slice_to(len), array2.slice_to(len));
(If you know that array1 is always longer than array2 then bytes::copy_memory(array1.mut_slice_to(array2.len()), array2) should also work.)
At the moment, the bytes version optimises the best, down to a memcpy call, but hopefully rustc/LLVM improvements will eventually take them all to that.
You could simply use copy_from_slice() and use Range & Co:
fn main() {
let mut dest = [0; 8];
let src = [1, 2, 3, 4];
dest[..4].copy_from_slice(&src);
assert_eq!(dest, [1, 2, 3, 4, 0, 0, 0, 0]);
}
Inverse case:
fn main() {
let src = [1, 2, 3, 4, 5, 6, 7, 8];
let mut dest = [0; 4];
dest.copy_from_slice(&src[2..6]);
assert_eq!(dest, [3, 4 ,5, 6]);
}
Combined case:
fn main() {
let src = [1, 2, 3, 4, 5, 6, 7, 8];
let mut dest = [0; 4];
dest[1..3].copy_from_slice(&src[3..5]);
assert_eq!(dest, [0, 4, 5, 0]);
}

How to specify const array in global scope in Rust?

When I tried to add a const array in the global scope using this code:
static NUMBERS: [i32] = [1, 2, 3, 4, 5];
I got the following error:
error: mismatched types:
expected `[i32]`,
found `[i32; 5]`
(expected slice,
found array of 5 elements) [E0308]
static NUMBERS2: [i32] = [1, 2, 3, 4, 5];
^~~~~~~~~~~~~~~
The only way I found to deal with this problem is to specify the length in the type:
static NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];
Is there a better way? It should be possible to create an array without manually counting its elements.
Using [T; N] is the proper way to do it in most cases; that way there is no boxing of values at all. There is another way, though, which is also useful at times, though it is slightly less efficient (due to pointer indirection): &'static [T]. In your case:—
static NUMBERS: &'static [i32] = &[1, 2, 3, 4, 5];
You can use const for that, here is an example:
const NUMBERS: &'static [i32] = &[1, 2, 3, 4, 5];

How to initialize three dimensional char array without using pointers in c

How to initialize three dimensional char array without pointers in c and access it?
I tried the following:
char card[1][3][15]={
{"iron","man"},
{"contagious","heide"},
{"string","middle"}
};
but I am getting
**Error:too many initializers**
**Warning: Array is only partially initialized**
Lets take a simple example...You can use your own values instead of these integers:
declaration:
int arr[2][3][4] = { { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} },
{ {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} } };
I hope, it is clear to you.
Considering your example itself:
I think it should be
char card[1][3][15]={ {"iron","man", "contagious"}};
What this means is that you can effectively create 3 char arrays each of length 15. Your first dimension of 1 doesn't have much effect.
So, you can make it like
char card[2][3][15]={ {"iron","man", "contagious"},
{"iron","man", "contagious"}};
So, for your simple understand, the number of rows indicate the first dimension, the number of columns in each row indicates the second dimension and the number of elements(in this case chars) in each column indicates the 3rd dimension.
So, now you can see that for the data in your question, you should declare the array as char char[3][2][15]
char card[1][3][15]={ { {"iron","man"},{"contagious","heide"},{"string","middle"}}
};
You should put another braces brackets inside. I think it will be helpful to you.

Resources