Swap digits of a floating point number

I'm following the 'rust by example' documentation since it is some time that I don't program in Rust, and I'm having some problem on the 2nd activity proposed in this page. Basically, It's asking me to swap the digits of a floating-point number, the firsts before and after the floating point. I created this function:

    fn reverse_floating_point(f:f32) -> f32{
        let is_positive = f.is_sign_positive();
        
        let clone = format!("{:.1}",f);
        let mut clone = clone.chars();
    
        // if number is negative, don't take the '-'
        let first: char = match is_positive {
            true => clone.next().unwrap(),
            false => {
                clone.next();
                clone.next().unwrap()
            },
        };
    
        let last = clone.last().unwrap();
    
        // if number is negative, add the '-'
        match is_positive {
            true => format!("{last}.{first}").parse::<f32>().unwrap(),
            false => format!("-{last}.{first}").parse::<f32>().unwrap(),
        }
    }

which it seems to work but it is not the intended way that the book suggests since it should be an exercise for tuples, probably with a function that takes an f32 and returns a (i32,i32), which can be easily swapped. How can I do it?

EDIT:
I'm starting with an f32 and not with a (i32,i32) because the function is supposed to be an implementation for the Matrix tuple struct that has for fields (f32,f32,f32,f32). For reference, this is what I wrote:

  use std::fmt;
  
  #[derive(Debug)]
  pub struct Matrix(
      pub f32,
      pub f32,
      pub f32,
      pub f32
  );
  
  impl Matrix {
      pub fn transpose(&self) -> Matrix {
          Matrix(
              Self::reverse_floating_point(self.0),
              Self::reverse_floating_point(self.1),
              Self::reverse_floating_point(self.2),
              Self::reverse_floating_point(self.3),
          )
      }
  
      fn reverse_floating_point(f:f32) -> f32{
          let is_positive = f.is_sign_positive();
          
          let clone = format!("{:.1}",f);
          let mut clone = clone.chars();
      
          // if number is negative, don't take the '-'
          let first = match is_positive {
              true => clone.next().unwrap(),
              false => {
                  clone.next();
                  clone.next().unwrap()
              },
          };
      
          let last = clone.last().unwrap();
      
          // if number is negative, add the '-'
          match is_positive {
              true => format!("{last}.{first}").parse::<f32>().unwrap(),
              false => format!("-{last}.{first}").parse::<f32>().unwrap(),
          }
      }
      
  }
  
  impl fmt::Display for Matrix {
      fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
          write!(f,"( {:.1}, {:.1} )\n( {:.1}, {:.1} )",self.0,self.1,self.2,self.3)
      }
  }

I think you're misreading the question. It's asking you to swap the positions of four numbers, not swap the digits inside a number.

Initially, the Matrix is

let matrix = Matrix(1.1, 1.2, 2.1, 2.2);

To make it clearer, let's replace the numbers with letters:

let matrix = Matrix(a, b, c, d);
// where a = 1.1, b = 1.2, c = 2.1, d = 2.2

The original matrix would be printed as

( a  b )
( c  d )

After a transpose, it would be printed as

( a  c )
( b  d )

with the positions of b and c swapped with each other.

5 Likes

It explicitly says "transpose".

Though 'reverse the digits of a number" is an interesting 'interview question'! (No matter how bad an idea using those in an actual interview is)

But you don't have to know what transpose() means, because:

Add a transpose function using the reverse function as a template, which accepts a matrix as an argument, and returns a matrix in which two elements have been swapped.

It is asking for matrix elements to be swapped, not for digits.


That said, the example could be better. The current example can be ambiguous if it's the only thing you read, because the resulting matrix would indeed be the same if you swapped the digits. An unambiguous example could be:

Matrix:
( 1.2 3.4 )
( 5.6 7.8 )
Transpose:
( 1.2 5.6 )
( 3.4 7.8 )

To be fair, the authors of the exercise probably expected the reader to read all of the instruction, and not just glance at the example.