Question 2: What is the output of the code below?*
String input_text = “ACBCBABC”;
String needle = "ABC";
Array[String] text_letters = split("", input_text);
Array[String] needle_chars = split("", needle);
Int needle_found = 0;
HashMap result = {};
public HashMap get_parsed_structure( String letter, String prev_key, String prev_text, Array[String] array_of_chars ) {
HashMap partial_hash = {};
Int count = 0;
while( text_letter = shift(array_of_chars) ) {
if( text_letter == letter ) {
count++;
String key = sprintf("%s%d%s", prev_key, count, letter)
String current_text = sprintf("%s%s", prev_text, letter)
if( current_text == needle ) {
needle_found++
} else {
partial_hash->{key} = {
"rest_array" : array_of_chars,
"text" : current_text
}
}
}
}
return partial_hash;
}
public main {
foreach String needle_letter (needle_chars) {
HashMap partial_result = {}
foreach String hash_key ( keys result ) {
partial_result = merge_2_hashmaps( partial_result, get_parsed_structure( needle_letter, hash_key, result->{hash_key}->{text}, result->{hash_key}->{rest_array} ) );
}
if( needle_found == 0 and not( result ) ) {
// print "First iteration; "
result = get_parsed_structure( needle_letter, "", "", text_letters )
} else {
result = partial_result
}
}
print "Number of needles: " + needle_found;
}
NOTES (below you can find some representations used in the pseudocode):
-
The “split” function splits a String value into an array of characters
-
The “shift” function returns the first element of an array and deletes it from the array
-
The “keys” function returns an array with all the keys of a hashmap
-
The hashmap is represented as a JSON hash { “key” : “value” }
-
The function “merge_2_hashmaps” returns the concatenated hashmap of 2 hashmaps
-
The construction “foreach String value (array)” iterates through the whole array, and the value contains the element in each iteration
Number of needles: 2
Number of needles: 5
Error
Number of needles: 0
Question 3: What would be the output of the code above if the array_of_chars was transmitted as a reference (pointer) and the print command was uncommented?*
First iteration; Number of needles: 5
First iteration; First iteration; First iteration; Number of needles: 0
First iteration; First iteration; First iteration; Number of needles: 5
First iteration; First iteration; First iteration; Number of needles: 2
I try to trace the algorithm in order to obtain the actual result but I get stuck every time, I’m not so familiar with the programming language. Please provide an answer with an explanation. Thank you so much!