# Rosetta Challenge! -- Reverse a String

**URL:** <https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644>\
**Category:** Coding Questions\
**Created:** [May 8, 2020, 7:34pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644 "2020-05-08T19:34:09Z")\
**Posts on this page:** 13\
**Page:** 2

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [May 9, 2020, 7:51pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/21 "2020-05-09T19:51:27Z")

</div>

On Python mode it outputs: 🐍

(u’\xe0\xe9\xef\xf5\xfb’, u’I\U0001f496\U0001f3ae!’, u’as\u20dddf\u0305\u0305’)

àéïõû I💖🎮! as⃝df̅̅

ûõïéà !🎮💖I ̅̅fd⃝sa

 

```auto
# Discourse.Processing.org/t/rosetta-challenge-reverse-a-string/20644/21
# GoToLoop (2020/May/09)

TEXTS = u'àéïõû', u'I💖🎮!', u'as⃝df̅̅'

def setup():
    print TEXTS
    print TEXTS[0], TEXTS[1], TEXTS[2]
    print reverseStr(TEXTS[0]), reverseStr(TEXTS[1]), reverseStr(TEXTS[2])
    exit()

def reverseStr(s): return s[::-1]

```

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [May 9, 2020, 10:44pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/22 "2020-05-09T22:44:52Z")

</div>

> [@noel](#):
>
> An example of what I mean is the task [Draw a sphere.](https://rosettacode.org/wiki/Draw_a_sphere#Processing) Should it be responded as it is, or like Phyton, right below it which takes a third of the page? What criteria should be prioritized?

Great question. I think it is case-by-case. My personal approach has been “both are good, but simple first.”

So if something is easy to do in Processing – like draw a box – show the built-in, the same way that you would show a beginner who asked to draw a box how to use box().

Then, as a second example. a supplemental approach is to build your own box out of six planes. This is really useful for animated morphs, per-face texture control, etc., which you can’t do with `box()`. So ideally we’d have both DrawASphere and DrawASphereVertex – the simple but less flexible way, and then more complex, low-level / customizable ways.

This is kind of how the built-in Processing example set already works with examples like TextureCube – although they are not systematic.

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 10, 2020, 10:37am UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/23 "2020-05-10T10:37:55Z")

</div>

In order to better understand what is happening, I started to solve the [UTF-8 encode and decode](http://rosettacode.org/wiki/UTF-8_encode_and_decode) related to this task.  
The task is :

 ![good](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/2/20320490d7e84d167d8a9cfe47343bf1c718e854.jpeg)  
My working stage is: ![wrong](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/8/88a70aa29563524323eff6bc2bbad4d810e807da.jpeg)  
Where I ran again in problems because the last one is also a combined character.  
I can´t believe this isn’t possible in java. It must be possible at byte level.

```auto
import java.nio.charset.StandardCharsets;
import java.util.Formatter;
int t = 50; 
int tel;

Character[] chars = {'A', 'ö', 'Ж', '€', '?'}; // I changed last character because "\u1D11E" the Musical Symbol G Clef
                                               // can't be displayed in the editor it gives the errot "Invalid character constant "

void setup() {
  size(740, 200);
  background(255);
  fill(0);
  textSize(15);
  text("Character Name Unicode UTF-8 encoding (hex)", 25, 30);
  text("-------------------------------------------------------------------------------", 25, 50);
  for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11}) {
    byte[] encoded = utf8encode(codepoint);
    Formatter formatter = new Formatter();
    for (byte b : encoded) {
      formatter.format("%02X ", b);
    }
    String encodedHex = formatter.toString();
    int decoded = utf8decode(encoded);
    println(decoded);
    t += 25;    
    text(chars[tel], 30, t); 
    text(Character.getName(codepoint), 130, t);
    text("U+"+hex(chars[tel]), 450, t);
    text(encodedHex, 550, t);
    tel++;
  }
}

final byte[] utf8encode(int codepoint) {
  return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}

int utf8decode(byte[] bytes) {
  return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}

```

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 10, 2020, 12:51pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/24 "2020-05-10T12:51:43Z")

</div>

Still stuck.  
Why gives this code

> 11 1D 45 00

instead of

> D8 34 DD 1E

```auto
import java.nio.charset.StandardCharsets;

byte ar[] = "\u1D11E".getBytes(StandardCharsets.UTF_16LE) ;
println("byte length = "+ar.length);
for(int i = 0; i < ar.length; i++) print(hex(ar[i])+" ");

```

---

<div class="post-metadata">

**Author:** ![monkstone](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/monkstone/32/64_2.png) [@monkstone](https://discourse.processing.org/u/monkstone)\
**Post date:** [May 11, 2020, 7:04am UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/25 "2020-05-11T07:04:53Z")

</div>

@jeremydouglass this is kind of a non-problem in JRubyArt (propane and PiCrate), because the ruby code in JrubyArt sketches is just ruby code.

```ruby
str = 'àéïõû'
puts str.class
puts str.inspect
puts str.respond_to? :reverse
puts str.reverse
jstring = str.to_java
puts jstring.inspect
puts jstring.respond_to? :reverse

```

output:-

```bash
String
"àéïõû"
true
ûõïéà
#<Java::JavaLang::String:0x61ab6521>
false

```

So it possible to do static analysis on ruby code using such useful tools as `rubocop`, `reek` etc. Further rubocop has an autocorrect option, useful for correcting indentations, and other useful style changes, it is normal to use single quotes for strings, unless doing interpolation. Fortunately most of the time we do not need to coerce ruby to java before applying processing methods (generally jruby just does the right thing) but occasionally it is necessary, usually where the [java method signature](https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby) has been overloaded. This one of the reasons I encourage JRubyArt users to ignore many java convenience methods that are generally available in ruby (I despair at seeing people use for loops, that is certainly not the ruby way) but equally I’m not very fond of perlisms.

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 14, 2020, 4:36pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/26 "2020-05-14T16:36:40Z")

</div>

> [@jeremydouglass](#):
>
> I honestly don’t see the point of that part of the task for most Processing users.

I agree and disagree. If P5 is used as a jumping-off point to learn to code, sooner or later one will be confronted with Unicode.  
I’ve spent quite some hours now, to dig into this, and I want to leave some links with tutorials for “dummies” for whom is interested. [One,](https://betterexplained.com/articles/unicode/) [two](https://www.bignerdranch.com/blog/elixir-and-unicode-part-1-unicode-and-utf-8-explained/),[three](https://www.bignerdranch.com/blog/elixir-and-unicode-part-2-working-with-unicode-strings/),[four.](https://www.unicode.org/faq/basic_q.html)

With a better understanding, I was able to solve the UTF-8 encode and decode task and already posted it there. It was asked to start with the code-points, but I think it can be used as a nice tool to analyze Unicode. So

> **here**
>
> ```auto
> import java.nio.charset.StandardCharsets;
> 
> String str = "ऒॐѬЩ∰⋫";
>   
> void setup() {
> size(850, 280);
> background(255);
> fill(0);
> textSize(16);
> int tel_1 = 80;
> int tel_2 = 50;
> text("Char Name Unicode UTF-8 (encoding) Decoded", 40, 40);
> char[] myBuffer = str.toCharArray();
> int[] code_points = new int[myBuffer.length];
> for (int i = 0; i < str.length(); i++) {
> println(hex(myBuffer[i]));
> code_points[i] = int(myBuffer[i]);
> }
> printArray( code_points);
> for (int cp : code_points) {  
> byte[] encoded = new String(new int[]{cp}, 0, 1).getBytes(StandardCharsets.UTF_8);
> for (byte b : encoded) {                                                    
> text(hex(b), tel_2+530, tel_1);
> tel_2 += 30;
> }
> text(char(cp), 50, tel_1);
> text(Character.getName(cp), 100, tel_1);
> String unicode = hex(cp);
> while (unicode.length() > 4 && unicode.indexOf("0") == 0) unicode = unicode.substring(1);
> text("U+"+unicode, 450, tel_1);
> Character decoded = char(new String(encoded, StandardCharsets.UTF_8).codePointAt(0));
> text(decoded, 750, tel_1);
> tel_1 += 30; tel_2 = 50;
> }
> }
> 
> ```

is a slightly modified version to be able to past a text string. Processing accepts more characters then I expected, but no emojis. (I don’t know what platform @GoToLoop used to display the emojis ) The android version(At least APDE) does accept quite a few.

 ![uni_encode](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/4/42b3b683036a365b1636c709a735333376b60584.jpeg)

I started at byte level searching in the string and filling the space left after the leading and continuation bits, but soon I realized that the code would be quite large, so I went one level up using UnicodeBlocks to filter the string. With this, I was able to solve the “Extra credit task” for P5.java as well with a reverseSring() function. See

> **here**
>
> ```auto
> import java.lang.Character.UnicodeBlock;
> 
> String str = "as⃝df̅";
> 
> void setup() {
> size(350, 150);
> background(255);
> fill(0);
> textSize(30);
> textAlign(CENTER);
> text(str, width/2, height/3);    
> String str1 = reverseString(str);
> text(str1, width/2, 2*height/3);
> }   
> 
> String reverseString(String inStr) {
> char[] myBuffer = inStr.toCharArray();
> StringBuffer sb = new StringBuffer();
> String mb = "";
> for (int i = 0; i < inStr.length(); i++) {
> UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
> if (ub == UnicodeBlock.COMBINING_DIACRITICAL_MARKS
> //|| ub == UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS
> //|| ub == UnicodeBlock.COMBINING_DIACRITICAL_MARKS_SUPPLEMENT
> //|| ub == UnicodeBlock.COMBINING_HALF_MARKS
> ) mb = mb+'1'; // Storing 'mark' indexes
> else mb = mb+'0';   
> sb.append(myBuffer[i]);              
> }
> String nmb = new StringBuilder(mb).reverse().toString();
> sb = sb.reverse();
> Integer bl = myBuffer.length;
> for (int i = 0; i < bl; i++) {
> if(nmb.charAt(i) == '1') {
> char temp = sb.charAt(i+1);
> sb.setCharAt(i+1, sb.charAt(i));
> sb.setCharAt(i, temp);
> }  
> }  
> return sb.toString();
> }
> 
> ```

Whoever set up this task knew how to ‘bully’, because the character in the middle is also of a combining type, so when out-comment the “ub == UnicodeBlock.COMBINING\_MARKS\_FOR\_SYMBOLS” line, the order is wrongly displayed again.

![reverse](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/1/1203769542a6b5a3ec0d055765b83ff2c28f5a45.jpeg)

@monkstone How does the extra credit task play out in JrubyArt ?

---

<div class="post-metadata">

**Author:** ![monkstone](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/monkstone/32/64_2.png) [@monkstone](https://discourse.processing.org/u/monkstone)\
**Post date:** [May 14, 2020, 7:34pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/27 "2020-05-14T19:34:51Z")

</div>

@noel since ruby-2.4 default encoding in ruby is unicode, so once more a facile challenge:-

given following emojis​:walking\_man: 🏎 🚔 🚐 we can do this in PiCrate (limitations of color etc).

```ruby
str = '🚶 🏎 🚔 🚐'
puts str.reverse

```

Output:-

```bash
🚐 🚔 🏎 🚶

```

Except it does not quite look that way in my monochrome terminal.

---

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [May 14, 2020, 10:15pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/28 "2020-05-14T22:15:16Z")

</div>

Hi @monkstone – great to see the unicode emoji support in ruby. I think maybe (?) @noel was wondering about if ruby can reverse the extra challenge from the Rosetta Wiki task, which isn’t just using individual unicode characters – it is using modifiers and combining marks, which then may fail in unique ways if they are simply reversed:

> [@jeremydouglass](#):
>
> as⃝df̅

---

<div class="post-metadata">

**Author:** ![monkstone](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/monkstone/32/64_2.png) [@monkstone](https://discourse.processing.org/u/monkstone)\
**Post date:** [May 15, 2020, 9:11am UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/29 "2020-05-15T09:11:52Z")

</div>

Ruby fails with that set of characters, but least we can inspect why.

```ruby
str = 'as⃝df̅'
chars = str.scan(/[[:graph:]]/)
puts chars.inspect

```

output:-

```bash
["a", "s", "⃝", "d", "f", "̅"]

```

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 15, 2020, 12:03pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/30 "2020-05-15T12:03:39Z")

</div>

> [@monkstone](#):
>
> least we can inspect why.

I guess when you know the reason, there must be a solution. 🙂

---

<div class="post-metadata">

**Author:** ![monkstone](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/monkstone/32/64_2.png) [@monkstone](https://discourse.processing.org/u/monkstone)\
**Post date:** [May 15, 2020, 1:12pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/31 "2020-05-15T13:12:43Z")

</div>

@noel You would think so, but I’ve trawled the internet, and none seem forthcoming. Found out lots of interesting stuff though, including [this on string composition.](https://www.honeybadger.io/blog/ruby-unicode-normalization/). Hey I trawled some more, and this works:-

```ruby
str = 'as⃝df̅'
puts str
chars = str.scan(/\X/) # splits into grapheme clusters
puts chars.inspect
rev_string = chars.reverse
puts rev_string.inspect
puts rev_string.join

```

output:-

```bash
as⃝df̅
["a", "s⃝", "d", "f̅"]
["f̅", "d", "s⃝", "a"]
f̅ds⃝a

```

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 15, 2020, 1:44pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/32 "2020-05-15T13:44:55Z")

</div>

Great! Now I believe that the challenge was fulfilled for all versions.

---

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [May 15, 2020, 5:45pm UTC](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644/33 "2020-05-15T17:45:10Z")

</div>

> [@jeremydouglass](#):
>
> So ideally we’d have both DrawASphere and DrawASphereVertex

I’ve added the "[DrawASphereVertex](https://rosettacode.org/wiki/Draw_a_sphere#Processing)’ as you sugested.

[Previous page](https://discourse.processing.org/t/rosetta-challenge-reverse-a-string/20644.md?page=1)
