I have a scenario where I want to perform an action if a string in a list of string matches the index in a list of ints (Generated based on String list )
The below is some pseudo code to try and articulate what I am trying to achieve.
List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];
//Pseudo code
wordList.forEach(word)) {
if (wordIndex item matches index of word) {
do something;
} else {
od something else;
}
}
it the if (wordIndex item matches index of word) where I am having a problem and would appreciate any ideas.
Just use for instead of forEach;
List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];
//Pseudo code
for (int i = 0; i < wordList.length; i++) {
if (wordIndex.contains(i)) {
do something;
} else {
od something else;
}
}
If I understand you correctly, you want to know if the index of a word is contained in you wordIndex list, i.e. you want to get all wordList items with an index that is stored in wordIndex.
There are two approaches to this:
Use Iterable.contains
In this case, we are simple checking if the current index is present in the wordIndex list.
for (var index = 0; index < wordList.length; index++) {
if (wordIndex.contains(index)) {
// do something
return;
}
// do something else
}
Loop through wordIndex
If you are just interested in the matching items, this approach is more reasonable.
Here, we loop through the index list and then simply get the matching elements in the wordList. However, you will not be able to take actions for the non-matching items:
for (final index in wordIndex) {
final word = wordList[index];
// do something
}
Related
I'm trying to make a code that removes all the elements from the array that are equal to a given value. For example an array = [hi, hello, hi, bye] value = hi, it would given an output hello bye
Here's my code:
int count = 0;
for(int i=0; i<stringArr.length;
if(stringArr[i].equals(value)){
count--;
for(int j= i; j<stringArr.length-1; j++){
stringArr[j] = stringArr[j+1];
}
i--;
}
}
Problem is instead of the expected output as: hello bye
It gives an output of:
hello hi bye bye
Try Java stream api:
String value = "hi";
String[] stringArr = new String[] {"hi", "hello", "hi", "bye"};
String[] results = Arrays.stream(stringArr)
.filter(it -> !it.equalsIgnoreCase(value))
.toArray(String[]::new);
The problem is that you are shifting the values left but not decrementing the length of the array in the outer for.
Assign stringArr.length to count and use it in the for.
Trading memory for speed, you could create a new array of the same length and only add in the first occurrence of what you want.
String[] removeEqual(String[]array,String val){
boolean found =false;
String[]out=new String[array.length];
int count=0;
for (int i=0;i<array.length;i++){
if(array[i].equals(val)){
if(!found){
out[count++]=val;
found=true;
}
else out[count++]=val;
}
}
return Arrays.copyOf(out, count);
}
You may like to consider separate functions for separate conditions such as removeLessThan and removeGreaterThan to keep it functionally coherent.
I don't recommend to do any manipulation to the original array, create a new one. Recycling is good for the planet, but may be very harmful in code. So if you want to stick to the Arrays only, then create a new array with and add all elements you want into the new array, but I think you can do better. Your approach is very "C" like, this is Java, you have a lot of better tools, than arrays.
One of them are streams and lambdas like this
#Test
public void example_lambdas() {
String[] array = {"hi", "hello", "hi", "bye"};
String[] result = Arrays.stream(array).filter(element -> !"hi".equals(element)).toArray(String[]::new);
System.out.println(Arrays.toString(result));
}
Another option is to use list
#Test
public void example_list() {
String[] array = {"hi", "hello", "hi", "bye"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Set<String> toBeRemoved = Collections.singleton("hi");
list.removeAll(toBeRemoved);
String[] result = list.toArray(new String[0]);
System.out.println(Arrays.toString(result));
}
An array has a fixed size that cannot be changed. Hence your result cannot be a two element array when you start with a four element array. If you want the result to be a two element array, then you will need to create a second array. If, however, you want the result to stay in the original array, then I suggest setting the excess array elements to null. The following code demonstrates.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
int count = stringArr.length;
for (int i = 0; i < count; i++) {
if (condition.equals("==")) {
if (stringArr[i].equals(value)) {
count--;
for (int j = i; j < stringArr.length - 1; j++) {
stringArr[j] = stringArr[j + 1];
}
stringArr[stringArr.length - 1] = null;
}
}
}
System.out.println(java.util.Arrays.toString(stringArr));
The above code prints the following:
[hello, bye, null, null]
EDIT
As requested, below code creates a new array that only contains the requested elements, i.e. the ones that were not removed from the original array.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
String[] temp = new String[stringArr.length];
int count = 0;
for (int i = 0; i < stringArr.length; i++) {
if (condition.equals("==")) {
if (!stringArr[i].equals(value)) {
temp[count++] = stringArr[i];
}
}
}
String[] result = new String[count];
for (int i = 0; i < count; i++) {
result[i] = temp[i];
}
System.out.println(Arrays.toString(result));
The above code prints the following:
[hello, bye]
In other words, result is a two element array.
Note that I assume that you only want to do array manipulation and you don't want to use classes in the JDK that most of the other answers have used.
I am trying to count the number of a specific field which is not empty and would like to use an array to store the field names based on whether they exist in the PDF form.
My code looks like this so far and it works as long as the field names in the array exists, if that field does not exist then the code breaks.
The SiteDeficiency_DeficiencyNumber_# could have 0 instances or anywhere up to 50 instances or so.
I did find that you can check if a name exists with this code but I can't seem to get it to work.
Any help is appreciated. I have coded simple things but maybe this is just too advanced for me.
This is what my code looks like so far:
var aFields = new Array("SiteDeficiency_DeficiencyNumber_1",
"SiteDeficiency_DeficiencyNumber_2",
"SiteDeficiency_DeficiencyNumber_3",
"SiteDeficiency_DeficiencyNumber_4",
"SiteDeficiency_DeficiencyNumber_5",
"SiteDeficiency_DeficiencyNumber_6");
var count = 0;
for (i = 0; i < aFields.length; i++) {
if (this.getField(aFields[i]).valueAsString != "") count++
}
event.value = count;
I tried incorporating this too
if(document.forms[0].SiteDeficiency_DeficiencyNumber_1)
{
...
}
I would really like the array at the beginning to populate with only the SiteDeficiency_DeficiencyNumber_# fields that exist and then have the array looped through to count which fields are not blank.
I tried doing this but still does not work.
var aFields = [];
for(i = 1; i <101; i++)
{
if(document.forms[0].("SiteDeficiency_DeficiencyNumber_"+i).valueAsString.length > 0) //Checks if field exists
{
aFields.push("SiteDeficiency_DeficiencyNumber_"+i); //adds field name to array
}
}
var count = 0;
for (a = 0; a < aFields.length; a++) {
if (this.getField(aFields[a]).valueAsString != "") count++ //counts field if not empty
}
event.value = count;
Try this code:
var count = 0;
for(var i = 0; i < this.numFields; i++)
{
if (this.getNthFieldName(i).indexOf("SiteDeficiency_DeficiencyNumber")!= -1){
if (this.getField(this.getNthFieldName(i)).valueAsString != "")
count = count +1
}
}
event.value = count;
The first if statement will check if name of the field contain string SiteDeficiency_DeficiencyNumber. If SiteDeficiency_DeficiencyNumber is present in the field naem then it will check the field value and increment accordingly.
Don't forget to upvote! let me know if you need anything else
Does my method look correct? I have a function called:
int searchInventory(const struct Item items[], const int sku_item,
const int size)
This function receives the address of an array of type Item (items[]), an integer for the sku number of the desired item, and an integer size representing the size of the array. I'm not sure if I used the flags correctly. Through the array I have to search for an item with the desired sku number and return the index of the matching item if it is found. If not found I have to return -1. New to this site, so I am not sure I have given all the needed info for you guys to help me. If you understand at all, please advise me.
for (i = 0; i < size; i++)
{
if (sku_item == items[i]._sku)
return i;
else
{
return -1;
}
}
for (i = 0; i < size; i++) {
if (sku_item == items[i]._sku) {
return i;
}
}
return -1;
You need to iterate over the whole array before declaring the item is not found. So move return -1 outside of the loop.
Here is my homework:
We'll say that 2 strings "match" if they are non-empty and their first chars are the same. Loop over and then return the given array of non-empty strings as follows: if a string matches an earlier string in the array, swap the 2 strings in the array. When a position in the array has been swapped, it no longer matches anything. Using a map, this can be solved making just one pass over the array.
allSwap(["ab", "ac"]) → ["ac", "ab"]
allSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "azz", "aaa"]
allSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "aj", "ai", "by", "bx"]
In the map, store the first letter as the key, and the most recent index of the key as the value. When a letter doesn't exist in the map, add it to the map. When a letter already exists in the map, remove it from the map and swap with that index.
/**
* Swaps strings in the array that have the same first letter,
* reading left to right. Once a string has been swapped,
* it will not be swapped again. The input array will be mutated.
*
* #param strings the strings to perform swaps from
* #return the strings after swapping
*/
public static String[] allSwap(final String[] strings) {
// map of first characters, and the index where they were last seen
final Map<Character, Integer> potentialSwap = new HashMap<>();
for (int thisIndex = 0; thisIndex < strings.length; thisIndex++) {
if (strings[thisIndex].isEmpty()) {
continue; // skip empty strings
}
final Character firstChar = strings[thisIndex].charAt(0); // box charAt(0)
// remove firstChar from the map. If it's not found, returns null
final Integer potentialIndex = potentialSwap.remove(firstChar);
if (potentialIndex != null) {
final int thatIndex = potentialIndex; // unbox potentialIndex
// swap values at thisIndex and thatIndex
final String temp = strings[thatIndex];
strings[thatIndex] = strings[thisIndex];
strings[thisIndex] = temp;
} else {
// save the index for possible swapping later
potentialSwap.put(firstChar, thisIndex); // box thisIndex
}
}
return strings;
}
Ideone Demo
public String[] allSwap(String[] strings) {
// map of first characters, and the index where they were last seen
Map<Character, Integer> map = new HashMap();
for (int i = 0; i < strings.length; i++) {
char firstChar = strings[i].charAt(0);
// box charAt(0)
// remove firstChar from the map. If it's not found, returns null
Integer removedIndex = map.remove(firstChar);
if (removedIndex != null) {
int j = removedIndex;
// unbox potentialIndex
// swap values at thisIndex and thatIndex
String temp = strings[j];
strings[j] = strings[i];
strings[i] = temp;
} else {
// save the index for possible swapping later
map.put(firstChar, i);
}
}
return strings;
}
This can also work !
public String[] allSwap(String[] strings) {
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=0;i<strings.length;i++){
if(!map.containsKey(strings[i].substring(0,1))){
map.put(strings[i].substring(0,1),i);
}
else{
String temp = strings[map.get(strings[i].substring(0,1))];
strings[map.get(strings[i].substring(0,1))] = strings[i];
strings[i] = temp;
map.remove(strings[i].substring(0,1));
}
}
return strings;
}
I came up with this code to try and sort out an array of strings (I don't want to use ints or imports as I'm trying to understand iteration loops), but it only rearranges the first two strings. Can anyone point out my mistakes?
public class Alpha8 {
public static void main(String[] args) {
String[] Names = {"O","B","K","S","D","M","N","A"};
String temp = null;
for(int i=0;i<Names.length;i++){
for(int j = i+1;j<Names.length;j++) {
if(Names[j].compareTo(Names[i])<0)
temp = Names[i];
Names[i] = Names[j];
Names[j] = temp;
for( i = 0;i<Names.length;i++){
System.out.println(Names[i]);
}
}
}
}
}
You have made two mistakes:
You are printing the array inside your 'swap' code. You should only print the array once the sorting is complete.
You only iterate through the array once. For a bubble sort (which is what you are implementing) you need to keep iterating through until no swaps occur.
The method should look something like:
boolean hasSwapped;
do {
hasSwapped = false;
for (int i = 1; i < names.size(); i++) {
if (names[i-1].compareTo(names[i]) > 0) {
swap(names[i-1], names[i]);
hasSwapped = true;
}
}
} while (hasSwapped);