Finding last five number from input stream - java

I have input stream of numbers coming like
1 3 5 6 5 6 7 43 54 3 2 ....
At any point of given time how to find the last five number ?

Or you could use a circular buffer:
private class CircularBuffer {
private int[] items;
private int index = 0;
private int size = 0;
public CircularBuffer(int size) {
items = new int[size];
}
public void add(int item) {
items[index] = item;
index = (index + 1) % items.length;
size = Math.min(size + 1, items.length);
}
public int get(int i) {
if (i < 0 || i >= size)
throw new IndexOutOfBoundsException();
return items[(index - size + i + items.length) % items.length];
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < size; ++i) {
builder.append(get(i));
builder.append(i < size - 1 ? ", " : "]");
}
return builder.toString();
}
}
Test code:
CircularBuffer b = new CircularBuffer(5);
for (int i = 1; i < 10; ++i) {
b.add(i);
System.out.println(b);
}
Output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]

You could save them in a Stack which would be the easiest and 'best' way to do it inmho.
If you (for whatever reason) can't or don't want to use an Stack I would suggest you to implement the "push" method for Arrays:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] numbers = new int[5];
while(true){ // as long as you expect numbers from your stream
push(numbers, sc.nextInt());
}
}
public static void push(int[] arr, int value){
for(int i = 1; i < arr.length; i++){
arr[i - 1] = arr[i];
}
arr[arr.length - 1] = value;
}
Assuming your Stream provides with you with Integers only, via STDIN, one per line - the numbers array now holds the last 5 inputs for you (or 0 as a default value in case less than 5 values arrived so far).
Greetings Tim

Related

How can I get the subset from an ArrayList?

I'm working on a problem that asks me to "Write a method that returns all of the subsets of the set formed by the integers 1 to N where N is passed to the method." If I pass N = 3 to the method my output should look like [[0], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]. My current output is [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]. Is there a way for me to print out the desired range like doing Arrays.copyOfRange() for the ArrayList? or is there another way of getting the subset with my desired output?;
import java.util.ArrayList;
import java.util.HashSet;
public class HW3 {
public static void main(String[] args) {
System.out.println(powerset(3));
}
public static ArrayList<HashSet<Integer>> powerset(int N) {
ArrayList<HashSet<Integer>> arrayList = new ArrayList<HashSet<Integer>>();
HashSet<Integer> arrayListNew = new HashSet<Integer>();
for (int i = 0; i <= N; i++)
arrayListNew.add(i);
for (int i = 0; i < (int) Math.pow(2, N); i++)
arrayList.add(arrayListNew);
return arrayList;
}
}
"Is there a way for me to print out the desired range like doing Arrays.copyOfRange() for the ArrayList?"
yes, use sublist() read more here
However, you don't need that for your question. The algorithm you are looking for should look sth like this
//1st for loop iterate through all the possible sizes for the hash set
for(){
//2nd for loop generate all possible combinations given the size
for(){
}
}
//might need to add the [0] urself at the end
public class HW3 {
static void printSubsets(int set[]) {
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
System.out.print("{ ");
for (int j = 0; j < n; j++)
if ((i & (1 << j)) > 0)
System.out.print(set[j] + " ");
System.out.println("}");
}
}
public static void main(String[] args) {
int n = 3;
int[] set = new int[n+1];
for(int i = 0; i<=n; i++){
set[i]=i;
}
printSubsets(set);
}}
The total number of subsets of any given set is equal to 2^ (no. of elements in the set). If we carefully notice it is nothing but binary numbers from 0 to 7 which can be shown as below:
000
001
010
011
100
101
110
111
Starting from right, 1 at ith position shows that the ith element of the set is present as 0 shows that the element is absent. Therefore, what we have to do is just generate the binary numbers from 0 to 2^n – 1, where n is the length of the set or the numbers of elements in the set.
Time complexity: O(n * (2^n)) as the outer loop runs for O(2^n) and the inner loop runs for O(n).
The more suitable way to do this is Backtracking
public class BacktrackTest {
public static void main(String[] args) {
powerset(3);
}
public static void powerset(int num) {
if (num >= 10 || num < 1) {
throw new IllegalArgumentException();
}
int[] chs = new int[num];
for (int i = 1; i <= num; i++) {
chs[i - 1] = i;
}
List<List<Integer>> resultList = new ArrayList<>();
backtrack(0, chs, new ArrayList<>(), resultList);
Collections.sort(resultList, (a, b) -> {
int len1 = a.size();
int len2 = b.size();
return len1 - len2;
});
System.out.println(resultList);
}
public static void backtrack(int index, int[] chs, List<Integer> tempList, List<List<Integer>> resultList) {
for (int i = index; i < chs.length; i++) {
tempList.add(chs[i]);
resultList.add(new ArrayList<>(tempList));
backtrack(i + 1, chs, tempList, resultList);
tempList.remove(tempList.size() - 1);
}
}
}
Java Fiddle Demo
Output result:

Using queue to rearrange every other integer

I'm trying to figure out how to take in an integer and rearrange them so that every alternating character is saved (So the [1, 2, 3, 4, 5, 6] would return [1, 4, 2, 5, 3, 6]). I think a queue would be the best to use for this problem so here's what I have so far. It returns [3, 1, 4, 5, 2, 6], but I'm not sure how I can get it to return the alternating form above :
import java.util.*;
public class everyOtherInteger {
public static void main(String[] args) {
Queue <Integer> sort = new LinkedList<Integer>();
String s = "123456";
for (int i = 0; i < s.length(); i++) {
sort.add(Integer.parseInt(s.charAt(i) + ""));
if (i%2 == 0) {
int a = sort.remove();
sort.add(a);
}
else {
}
}
System.out.println(sort);
}
}
Just build the list differently. No queue required.
You can add half the numbers at the start, the add the rest in-between each.
List<Integer> nums = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int limit = sc.nextInt(); // 6
int value = 1;
for (int i = 0; i < limit / 2; i++) {
nums.add(value++);
}
for (int i = 1; i < limit; i+=2) {
nums.add(i, value++);
}
System.out.println(nums); // [1, 4, 2, 5, 3, 6]
I would just add them one after the other in a single loop. The second element is simply the current one plus the offset where the offset is half the array length.
read in the number as a string.
and work with the character array of digits.
Scanner input = new Scanner(System.in);
String val = input.next();
List<Integer> result =new ArrayList<>();
char[] digits = val.toCharArray();
int half = digits.length/2;
for(int i = 0; i < half; i++) {
result.add(digits[i]-'0');
result.add(digits[i+half]-'0');
}
System.out.println(result);
For an input of 123456, prints
[1, 4, 2, 5, 3, 6]

Why is my selection sort program not giving the correct output for the last few numbers?

I've been going through this MOOC.fi Java course and got to the problem about developing a selection sort algorithm on this page (https://java-programming.mooc.fi/part-7/2-algorithms). I don't have the solutions, so I was wondering if anyone here could help me solve this problem. Basically, I got through all the steps uptil Part 4, but when I tried to make the selection sort method, my method only sorted the numbers correctly until it got to the second to last number, and then it started switching the numbers incorrectly. Can anyone look over my code and tell me where I went wrong?
import java.util.Arrays;
public class MainProgram {
public static void main(String[] args) {
// Testing methods
// Test Part 1
int[] numbers = {6, 5, 8, 7, 11};
System.out.println("Smallest: " + MainProgram.smallest(numbers));
// Testing Part 2
System.out.println("Index of the smallest number: " + MainProgram.indexOfSmallest(numbers));
// Testing Part 3
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 0));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 1));
System.out.println(MainProgram.indexOfSmallestFrom(numbers, 2));
// Testing Part 4
int[] numbers2 = {3, 2, 5, 4, 8};
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 1, 0);
System.out.println(Arrays.toString(numbers2));
MainProgram.swap(numbers2, 0, 3);
System.out.println(Arrays.toString(numbers2));
// Testing Part 5
int[] numbers3 = {8, 3, 7, 9, 1, 2, 4};
MainProgram.sort(numbers3);
}
// Part 1
public static int smallest(int[] array) {
int smallest = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
return smallest;
}
// Part 2
public static int indexOfSmallest(int[] array){
int smallest = array[0];
int i;
int finalIndex = 0;
for (i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 3
public static int indexOfSmallestFrom(int[] table, int startIndex) {
int smallest = table[startIndex];
int i = startIndex;
int finalIndex = 0;
for (i = startIndex; i < table.length; i++) {
if (table[i] < smallest) {
smallest = table[i];
finalIndex = i;
}
}
return finalIndex;
}
// Part 4
public static void swap(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Part 5
public static void sort(int[] array) {
int smallestIndex;
for (int i = 0; i < array.length; i++) {
smallestIndex = indexOfSmallestFrom(array, i);
swap(array, smallestIndex, i);
System.out.println(Arrays.toString(array));
}
}
}
Here is the wrong output:
[1, 3, 7, 9, 8, 2, 4]
[1, 2, 7, 9, 8, 3, 4]
[1, 2, 3, 9, 8, 7, 4]
[1, 2, 3, 4, 8, 7, 9]
[1, 2, 3, 4, 7, 8, 9]
[8, 2, 3, 4, 7, 1, 9]
[9, 2, 3, 4, 7, 1, 8]
In the 3 block you set the
finalIndex = 0;
It should be set to the startIndex

I am having trouble with a computer science program that I am working on. I finished the coding but I am having trouble with my Runner Class

Given a provided array, determine how many groups of a specified size exist.
For the array [1,1,1,2,2,2,3,3,3,4,5,6,7] , there are 7 groups with at least one, 3 groups with at
least 2, and 3 groups with at least 3. A group is a series of same values. 1 1 1 is a group of 3, but it also is
a group of 1 and 2. To count as a group, all values must be the same. 1 1 1 is a group of 3 because there
are 3 1s in a row.
Sample output:
[3, 3, 3, 3, 3, 9, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8]
size 1 count == 7
size 2 count == 6
size 3 count == 5
size 4 count == 3
size 5 count == 2
size 6 count == 1
My main code:
import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayStats {
int[] numArray;
int number;
public ArrayStats(int[] a) {
setArray(a);
}
public void setArray(int[] a) {
numArray = a;
}
public int getNumGroupsOfSize() {
int cnt = 0;
for (int i = 0; i < numArray.length - 1; i++) {
if (numArray[i] == numArray[i + 1])
cnt++;
for (int j = 0; j <= 9; j++) {
if (cnt == i)
number = cnt;
else if (cnt == 1)
number = 1;
}
}
return number;
}
public String toString() {
return "size count" + " == " + getNumGroupsOfSize() + Arrays.toString(numArray);
}
}
My runner code:
public class ArrayStatsRunner
{
public static void main(String args[])
{
int[] one = {3, 3, 3, 3, 3, 9, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
ArrayStats test = new ArrayStats(one);
System.out.println(test.toString());
System.out.println("size 1 count == "+test.getNumGroupsOfSize(1));
System.out.println("size 2 count == "+test.getNumGroupsOfSize(2));
System.out.println("size 3 count == "+test.getNumGroupsOfSize(3));
System.out.println("size 4 count == "+test.getNumGroupsOfSize(4));
System.out.println("size 5 count == "+test.getNumGroupsOfSize(5));
System.out.println("size 6 count == "+test.getNumGroupsOfSize(6));
}
}
There is couple of problems with this method:
public int getNumGroupsOfSize() {
int cnt = 0;
for (int x = 0; x < numArray.length - 1; x++) {
if (numArray[x] == numArray[x + 1]);
cnt++;
for (int y = 2; y <= 9; y++) {
if (cnt == y)
number = cnt;
else if (cnt == 1)
number = 1;
}
}
return number;
}
Here is only some of the problems:
1. lets look at the second line:
for (int x = 0; x < numArray.length - 1; x++)
x < numArray.length - 1 will cause a problem because you wont check the last index of the array.
side note: it's a custom to use the letter i (index) and not x or y. If you are doing for loop inside for loop the custom is to do:
for (int i = 0; i < numArray.length - 1; i++)
{
for (int j = 0; j < numArray.length - 1; j++)
{
//some line of code
}}
This line of code if (numArray[x] == numArray[x + 1]);will do nothing because you put ; in the end of the row. Even if numArray[x] == numArray[x + 1]is true it wont do cnt++;.
Please check and learn from this code:
public class Main {
public static void main(String [] args)
{
int[] nums = {3, 3, 3, 3, 3, 9, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
System.out.println(+getGroupSize(nums,9)); //prints 1
System.out.println("size two== "+groupCount(nums,2)); //prints 6
System.out.println("size three== "+groupCount(nums,3));//prints 5
int[] nums2={1,1,1,2,2,2,3,3,3,4,5,6,7};
System.out.println(+getGroupSize(nums2,1)); //prints 3
System.out.println("size two== "+groupCount(nums2,2)); //prints 3
System.out.println("size two== "+groupCount(nums2,3)); //prints 3
System.out.println("size two== "+groupCount(nums2,5)); //prints 0
}
public static int getGroupSize(int[] array, int specificNumber ) {
/*This method prints the number of times a specific number exist in a array.
example: if the input of specificNumber is 3. in this array:
int[] nums = {3, 3, 3, 3, 3, 9, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
the method will return 5.
if the number is 9 is method will return 1. if number is 7 the method will return 3
*/
int groupCount = 0; //counts the number of times a specific number exist in a array
for (int i = 0; i <= array.length - 1; i++) { //this for loop will check every number in array
if (array[i] ==specificNumber) {
groupCount++;// if the current number of the array is the specificNumber, then the count will do plus one
}
}
return groupCount; //return the count
}
public static int groupCount(int[] array, int groupSize)
{
int groupCount=0;
int currentGroup=array[0]; //initialize the current group to be the first group of the array
if(getGroupSize(array, array[currentGroup])>=groupSize)
{ //check the size of the first group
groupCount++;
}
for (int i = 0; i <= array.length - 1; i++) {
if (array[i] !=currentGroup) { //checks if the current number is equal to the current group value
if(getGroupSize(array, array[i])>=groupSize)
{
groupCount++;
}
currentGroup=array[i]; // restart the currentGroup to be the current valume of the array
}
} //end of for loop
return groupCount;
}
private static void print(int [] array) {
for (int i = 1; i < 10; i++) {
System.out.println("size " +i+" group:" +groupCount(array, i));
}
}
}

How to split a string array into small chunk arrays in java?

Below is the example of the code snippet which needs the help
Example:
[1,2,3,4,5]
if the chunk size is 1, [1,2,3,4,5]
if the chunk size is 2, [1,2] and [3,4] and [5]
if the chunk size is 3, [1,2,3] and [4,5]
if the chunk size is 4, [1,2,3,4] and [5]
Java (from comment):
int counter = 0;
for (int i=0; i<array.length; i++) {
if (count == chunksize) {
//do something and initialize
counter = 0;
}
counter++;
}
You can use Arrays.copyOfRange(int[] original, int from, int to)
The code could be something like this:
int chunk = 2; // chunk size to divide
for(int i=0;i<original.length;i+=chunk){
System.out.println(Arrays.toString(Arrays.copyOfRange(original, i, Math.min(original.length,i+chunk))));
}
Just stumbled upon this post after encountering the same question. Here is how I solved it (I used Arrays.copyOfRange():
public static int[][] splitArray(int[] arrayToSplit, int chunkSize){
if(chunkSize<=0){
return null; // just in case :)
}
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.length % chunkSize; // if rest>0 then our last array will have less elements than the others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for the 'rest'
// now we know how many arrays we need and create our result array
int[][] arrays = new int[chunks][];
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for(int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++){
// this copies 'chunk' times 'chunkSize' elements into a new array
arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
}
if(rest > 0){ // only when we have a rest
// we copy the remaining elements into the last chunk
arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
}
return arrays; // that's it
}
And the results:
chunkSize = 1
[1]
[2]
[3]
[4]
[5]
chunkSize = 2
[1, 2]
[3, 4]
[5]
chunkSize = 3
[1, 2, 3]
[4, 5]
chunkSize = 4
[1, 2, 3, 4]
[5]
chunkSize = 5
[1, 2, 3, 4, 5]
chunkSize = 6
[1, 2, 3, 4, 5]
If you don't mind importing Google Guava and converting to a List, there is a method for partitioning Lists:
https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-
The following may achieve the desired result:
List<Integer> listToBeSplit = Arrays.asList(sourceArray);
int chunkSize = 3;
Lists.partition(listToBeSplit, chunkSize);
Using pure Java 8:
public class Chunk {
public static void main(String[] args) {
int[] input = {1,2,3,4,78,999,-1,456};
int chunkSize = 3;
int[][] chunked = chunk(input, chunkSize);
Arrays.stream(chunked)
.map(Arrays::toString)
.forEach(System.out::println);
}
public static int[][] chunk(int[] input, int chunkSize) {
return IntStream.iterate(0, i -> i + chunkSize)
.limit((long) Math.ceil((double) input.length / chunkSize))
.mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
.toArray(int[][]::new);
}
}
[1, 2, 3]
[4, 78, 999]
[-1, 456]
import java.util.Arrays;
public class ArrayChunk {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
int[][] chunks1 = ArrayChunk(array, 1);
print(chunks1);
int[][] chunks2 = ArrayChunk(array, 2);
print(chunks2);
int[][] chunks3 = ArrayChunk(array, 3);
print(chunks3);
}
public static int[][] ArrayChunk(int[] array, int chunkSize) {
int numOfChunks = (int) Math.ceil((double) array.length / chunkSize);
int[][] output = new int[numOfChunks][];
for (int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
//
return output;
}
private static void print(int[][] output) {
//
System.out.println("======================");
for (int[] x : output)
System.out.println(Arrays.toString(x));
}
}
======================
[1]
[2]
[3]
[4]
[5]
======================
[1, 2]
[3, 4]
[5]
======================
[1, 2, 3]
[4, 5]
Try this,
Iterate it and check to give the chunk size.
int chunkSize = userInput;
// iterate and check the condition
char[] resultArray = Arrays.copyOfRange(inputArray, start, end);
start = start + end; // check whether the start will exceeds the length of the array
public static int[][] chunkArray(int[] array, int chunkSize) {
// first we need to get number of chunks by dividing length by chunkSize.
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
// we declare 2d array to save in the chunks
int[][] output = new int[numOfChunks][];
for(int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
return output;
}
for(int i=0;i<list.size();){
ArrayList<Integer>row = new ArrayList<Integer>();
int k=0;
while(k < chunksize){
chunk.add(list.get(i));
i++;
k++;
}
System.out.println(chunk);
nestedlist.add(chunk);
}
where list is a 1 dimension array and chunk is a nested array of size chunksize
In general you could use Arrays.copyOfRange to copy
This should do the trick
public static List<String> split(String string, int chunk) {
Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
+ "}[0-9]+)|[0-9]+");
Matcher matcher = pattern.matcher(string);
List<String> result = new ArrayList<String>();
while (matcher.find())
result.add("[" + matcher.group() + "]");
return result;
}
Test code:
for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
System.out.println("test for chunk size: " + chunkSize);
for (String string : split("[1,2,3,4,5]", chunkSize))
System.out.format("\t%s\n", string);
}
Output:
test for chunk size: 1
[1]
[2]
[3]
[4]
[5]
test for chunk size: 2
[1,2]
[3,4]
[5]
test for chunk size: 3
[1,2,3]
[4]
[5]
test for chunk size: 4
[1,2,3,4]
[5]
test for chunk size: 5
[1,2,3,4,5]
public class ArrayChunk {
public static void main(String[] args) {
String[][] chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 2);
System.out.println("Array with chunk size 2");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 3);
System.out.println("Array with chunk size 3");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 4);
System.out.println("Array with chunk size 4");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 5);
System.out.println("Array with chunk size 5");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
}
private static String[][] chunkArray(String[] array, int chunkSize) {
int chunkedSize = (int) Math.ceil((double) array.length / chunkSize); // chunked array size
String[][] chunked = new String[chunkedSize][chunkSize];
for (int index = 0; index < chunkedSize; index++) {
String[] chunk = new String[chunkSize]; // small array
System.arraycopy(array, index * chunkSize, chunk, 0, Math.min(chunkSize, array.length - index * chunkSize));
chunked[index] = chunk;
}
return chunked;
}
}
Output
Array with chunk size 2
1,2
3,4
5,6
7,8
9,null
Array with chunk size 3
1,2,3
4,5,6
7,8,9
Array with chunk size 4
1,2,3,4
5,6,7,8
9,null,null,null
Array with chunk size 5
1,2,3,4,5
6,7,8,9,null
Easy way to do so,
int loopcount = employeeList.size() / constCount;
int leftcount = employeeList.size() % constCount;
for (int i = 0; i < loopcount - 1; i++) {
//query.setParameterList("values"+i, employeeList.subList(tempCount, tempCount + constCount));
System.out.println(employeeList.subList(tempCount, tempCount + constCount));
tempCount = tempCount + 1000;
}
public class SplitArrayIntoChunks {
public static void main(String[] args) {
int[] in = {1,2,3,4,5};
chunks(in, 2);
}
private static void chunks(int[] in, int chunkSize) {
List<int[]> outList = new ArrayList<>();
int i = 0;
while (i < in.length) {
int[] out = Arrays.copyOfRange(in, i, Math.min(i + chunkSize, in.length));
outList.add(out);
out = new int[chunkSize + 1];
i += chunkSize;
}
for (int[] ol: outList) {
System.out.print("[");
Arrays.stream(ol).forEach(System.out::print);
System.out.println("]");
}
}
}
// Result: [12]
[34]
[5]
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let idx = 0;
let count = 0;
let tempList = [];
let resultList = [];
let splitSize = 2
while (idx <= array.length)
{
tempList.push(array[idx++]);
count++;
if (count == splitSize)
{
resultList.push(tempList);
tempList = [];
count = 0;
}
}
if (!tempList.length)
{
resultList.push(tempList);
}
console.log(resultList);
This can be done in a few lines of code
int i=0;
while (i<array.length) {
System.out.println(Arrays.toString(Arrays.copyOfRange(array, i, Math.min(array.length, i+chunkSize))));
i+=chunkSize;
}
Q.Split the array into chunks with a specified size?
Answer:
public class SplitArray {
public static void main(String[] args) {
int[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int splitSize = 3;
/* expected Output
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
*/
List<int[]> list = splitArray(original, splitSize);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));
}
public static List<int[]> splitArray(int[] array, int splitSize) {
List<int[]> result = new ArrayList<>();
int len=array.length;
int arr[] = null;
int size = splitSize;
int k=0;
for(int i=0;i<array.length;i++) {
if(k==0)
arr=new int[size];
arr[k]=array[i];
k++;
if(k>size-1) {
k=0;
result.add(arr);
len=len-size;
if(len<splitSize) {
size=len;
}
}
}
return result;
}
}
you can use the methode toCharArray :
// Custom input string
String str = "12345678";
// Creating array and storing the array
// returned by toCharArray() method
char[] ch = str.toCharArray();
// Lastly printing the array elements
for (char c : ch) {
System.out.println(c);
}
see more : https://www.geeksforgeeks.org/convert-a-string-to-character-array-in-java/

Categories

Resources