Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

mapBully challenge

Hi,

 I am working on below challenge
http://codingbat.com/prob/p197888


[/Map-1 > mapBully
prev  |  next  |  chance


Modify and return the given map as follows: if the key "a" has a value, set the key "b" to have that value, and set the key "a" to have the value "". Basically "b" is a bully, taking the value and replacing it with the empty string.

mapBully({"b": "dirt", "a": "candy"}) → {"b": "candy", "a": ""}
mapBully({"a": "candy"}) → {"b": "candy", "a": ""}
mapBully({"b": "carrot", "c": "meh", "a": "candy"}) → {"b": "candy", "c": "meh", "a": ""}

how below got below result

mapBully({"a": "candy"}) → {"b": "candy", "a": ""}

there is no b in the input map right then how it came in the output map?
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

public Map<String, String> mapBully(Map<String, String> map) {
  String val=map.get("a");
  String backup=val;
  map.put("b",backup);
  map.put("a","");
  
  return map;
}

Open in new window


failing two tests.
Expected      Run            
mapBully({"b": "dirt", "a": "candy"}) → {"b": "candy", "a": ""}      {"b": "candy", "a": ""}      OK      
mapBully({"a": "candy"}) → {"b": "candy", "a": ""}      {"b": "candy", "a": ""}      OK      
mapBully({"b": "carrot", "c": "meh", "a": "candy"}) → {"b": "candy", "c": "meh", "a": ""}      {"b": "candy", "c": "meh", "a": ""}      OK      
mapBully({"b": "carrot"}) → {"b": "carrot"}      {"b": null, "a": ""}      X      
mapBully({"c": "meh"}) → {"c": "meh"}      {"b": null, "c": "meh", "a": ""}      X      
mapBully({"c": "meh", "a": "sparkle"}) → {"b": "sparkle", "c": "meh", "a": ""}      {"b": "sparkle", "c": "meh", "a": ""}      OK      
please advise
Avatar of gudii9

ASKER

public Map<String, String> mapBully(Map<String, String> map) {
  if(map.containsKey("a")){
  String val=map.get("a");
  String backup=val;
  map.put("b",backup);
  map.put("a","");
  }
  return map;
}

Open in new window

above passes all tests. any improvements or alternate approaches?
>> any improvements
Yes.
1. Indent your code decently
2. There's no need to work with those temporary variables

public Map<String, String> mapBully(Map<String, String> map) {
    if (map.containsKey("a")) {
       map.put("b", map.get("a"));
       map.put("a","");
    }
    return map;
}

Open in new window

And you could have seen the code in the above post if you'd simply clicked the "Show Solution" button next to the "Go" button on the codingbat webpage you linked to.