Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #3356 > unrolled thread

Reversing a string without using array, classes and reverse function

Started byRubist Rohit <passionate_programmer@hotmail.com>
First post2011-04-21 22:54 -0500
Last post2011-04-23 16:16 -0500
Articles 20 — 12 participants

Back to article view | Back to comp.lang.ruby


Contents

  Reversing a string without using array, classes and reverse function Rubist Rohit <passionate_programmer@hotmail.com> - 2011-04-21 22:54 -0500
    Re: Reversing a string without using array, classes and reverse function spiralofhope <spiralofhope_rubyml@lavabit.com> - 2011-04-21 23:32 -0500
      Re: Reversing a string without using array, classes and reverse function Rubist Rohit <passionate_programmer@hotmail.com> - 2011-04-22 00:07 -0500
        Re: Reversing a string without using array, classes and reverse function Jose Calderon-Celis <josecalderoncelis@gmail.com> - 2011-04-22 02:45 -0500
          Re: Reversing a string without using array, classes and reverse function Stu <stu@rubyprogrammer.net> - 2011-04-22 03:32 -0500
            Re: Reversing a string without using array, classes and reverse function Stu <stu@rubyprogrammer.net> - 2011-04-22 03:43 -0500
              Re: Reversing a string without using array, classes and reverse function Larry Lv <larrylv1990@gmail.com> - 2011-04-22 04:24 -0500
          Re: Reversing a string without using array, classes and reverse function Rubist Rohit <passionate_programmer@hotmail.com> - 2011-04-22 06:56 -0500
    Re: Reversing a string without using array, classes and reverse function Stu <stu@rubyprogrammer.net> - 2011-04-22 03:16 -0500
    Re: Reversing a string without using array, classes and reverse function Robert Dober <robert.dober@gmail.com> - 2011-04-22 04:51 -0500
      Re: Reversing a string without using array, classes and reverse function Jose Calderon-Celis <josecalderoncelis@gmail.com> - 2011-04-22 09:42 -0500
        Re: Reversing a string without using array, classes and reverse function Brian Candler <b.candler@pobox.com> - 2011-04-23 06:11 -0500
          Re: Reversing a string without using array, classes and reverse function Robert Dober <robert.dober@gmail.com> - 2011-04-23 07:34 -0500
    Re: Reversing a string without using array, classes and reverse function Hans Mackowiak <hanmac@gmx.de> - 2011-04-22 05:33 -0500
    Re: Reversing a string without using array, classes and reverse function Harry Kakueki <list.push@gmail.com> - 2011-04-22 06:15 -0500
      Re: Reversing a string without using array, classes and reverse function spiralofhope <spiralofhope_rubyml@lavabit.com> - 2011-04-22 07:05 -0500
      Re: Reversing a string without using array, classes and reverse function Rubist Rohit <passionate_programmer@hotmail.com> - 2011-04-22 07:17 -0500
    Re: Reversing a string without using array, classes and reverse function Josh Cheek <josh.cheek@gmail.com> - 2011-04-23 13:33 -0500
      Re: Reversing a string without using array, classes and reverse function Duke Normandin <dukeofperl@ml1.net> - 2011-04-23 13:56 -0500
      Re: Reversing a string without using array, classes and reverse function Adam Prescott <adam@aprescott.com> - 2011-04-23 16:16 -0500

#3356 — Reversing a string without using array, classes and reverse function

FromRubist Rohit <passionate_programmer@hotmail.com>
Date2011-04-21 22:54 -0500
SubjectReversing a string without using array, classes and reverse function
Message-ID<152dbb1d1a91da817a7dd6e51045f007@ruby-forum.com>
I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above line
in loop?

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [next] | [standalone]


#3357

Fromspiralofhope <spiralofhope_rubyml@lavabit.com>
Date2011-04-21 23:32 -0500
Message-ID<20110421213116.27073f57@user-GA-MA785GM-US2H>
In reply to#3356
On Fri, 22 Apr 2011 12:54:16 +0900
Rubist Rohit <passionate_programmer@hotmail.com> wrote:

> I am trying this:
> 
> mystring = gets
> mystring.scan(/..$/) {|x| puts x}
> 
> It returns only the last character. Is it possible to add the above
> line in loop?

Here's something I stumbled through which seems to work.

- Using a regex of /.$/
- Slowly chomping away at the original string.
- Using another variable to build my result.



mystring = 'Hello, World!'
result = ''

fail = 0
until fail == "100" or mystring == '' do
  fail += 1
  mystring.match( %r{(.$)} )
  break if $~ == nil
  result += $~[1]
  mystring = mystring.chomp( $~[1] )
end

puts result




-- 
http://spiralofhope.com

[toc] | [prev] | [next] | [standalone]


#3360

FromRubist Rohit <passionate_programmer@hotmail.com>
Date2011-04-22 00:07 -0500
Message-ID<64b8f4ff033f8a95bcbe2ddfb71fb9e4@ruby-forum.com>
In reply to#3357
I attempted below given code, but it is neither displaying result nor 
error:

================CODE==========================
s = "This is to test reverse of a string"
len = s.length
for j in len..1 do
  mycommand = "s.scan(/.$/) {|x| puts x}"
  mycommand = mycommand.insert 7,"."
end
==============================================

What I am doing is to insert a period (.) in the seventh or eighth 
position on each loop.


spiralofhope wrote in post #994433:
> On Fri, 22 Apr 2011 12:54:16 +0900
>> I am trying this:
>>
>> mystring = gets
>> mystring.scan(/..$/) {|x| puts x}
>>
>> It returns only the last character. Is it possible to add the above
>> line in loop?
>
> Here's something I stumbled through which seems to work.
>
> - Using a regex of /.$/
> - Slowly chomping away at the original string.
> - Using another variable to build my result.
>
> mystring = 'Hello, World!'
> result = ''
>
> fail = 0
> until fail == "100" or mystring == '' do
>   fail += 1
>   mystring.match( %r{(.$)} )
>   break if $~ == nil
>   result += $~[1]
>   mystring = mystring.chomp( $~[1] )
> end
>
> puts result

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [prev] | [next] | [standalone]


#3366

FromJose Calderon-Celis <josecalderoncelis@gmail.com>
Date2011-04-22 02:45 -0500
Message-ID<BANLkTikMKVMmknL_JqwWnoPnWPXvfZ-S+A@mail.gmail.com>
In reply to#3360
[Note:  parts of this message were removed to make it a legal post.]

#!/usr/bin/env ruby
#
require 'rubygems'

puts "ruby #{RUBY_VERSION}"
s = "This is to test reverse of a string"
p s
len=s.length
mycommand=""
for j in 1..len do
  mycommand += s[-1*j]
end
p mycommand
Jose Calderon-Celis
5199906-7970
http://www.tm.com.pe/mensajes/



2011/4/22 Rubist Rohit <passionate_programmer@hotmail.com>

> I attempted below given code, but it is neither displaying result nor
> error:
>
> ================CODE==========================
> s = "This is to test reverse of a string"
> len = s.length
> for j in len..1 do
>  mycommand = "s.scan(/.$/) {|x| puts x}"
>  mycommand = mycommand.insert 7,"."
> end
> ==============================================
>
> What I am doing is to insert a period (.) in the seventh or eighth
> position on each loop.
>
>
> spiralofhope wrote in post #994433:
> > On Fri, 22 Apr 2011 12:54:16 +0900
> >> I am trying this:
> >>
> >> mystring = gets
> >> mystring.scan(/..$/) {|x| puts x}
> >>
> >> It returns only the last character. Is it possible to add the above
> >> line in loop?
> >
> > Here's something I stumbled through which seems to work.
> >
> > - Using a regex of /.$/
> > - Slowly chomping away at the original string.
> > - Using another variable to build my result.
> >
> > mystring = 'Hello, World!'
> > result = ''
> >
> > fail = 0
> > until fail == "100" or mystring == '' do
> >   fail += 1
> >   mystring.match( %r{(.$)} )
> >   break if $~ == nil
> >   result += $~[1]
> >   mystring = mystring.chomp( $~[1] )
> > end
> >
> > puts result
>
> --
> Posted via http://www.ruby-forum.com/.
>
>

[toc] | [prev] | [next] | [standalone]


#3370

FromStu <stu@rubyprogrammer.net>
Date2011-04-22 03:32 -0500
Message-ID<BANLkTik2HSDUWQgbZAT=LyNJ5bK+ZdWrmQ@mail.gmail.com>
In reply to#3366
On Fri, Apr 22, 2011 at 2:45 AM, Jose Calderon-Celis
<josecalderoncelis@gmail.com> wrote:

> for j in 1..len do
>  mycommand += s[-1*j]
>
>

very nice I like the use of your math. By multiplying the array index
by negative one your sending the index a reverse number while your for
loop traverses forward. This is perfect logic.

Here is a rewrite with my while loop:

s = "1234567890"
r=String.new
i = 1
while i <= s.length
  r << s[i*(-1)]
  i+=1
end
printf s
"0987654321"
 => "0987654321"
> y == x.reverse
true

[toc] | [prev] | [next] | [standalone]


#3371

FromStu <stu@rubyprogrammer.net>
Date2011-04-22 03:43 -0500
Message-ID<BANLkTikHB-1rtiifFqqBXmH0Xtr=KkyFeA@mail.gmail.com>
In reply to#3370
One more with ruby blocks (This would be the ruby way =) )

s = "1234567890"
r = String.new
s.length.times{|i| r << s[(i+1)*(-1)]}

r == s.reverse
true

cheers!!!

That was fun!!!... give me another =)

~Stu
On Fri, Apr 22, 2011 at 3:32 AM, Stu <stu@rubyprogrammer.net> wrote:
> On Fri, Apr 22, 2011 at 2:45 AM, Jose Calderon-Celis
> <josecalderoncelis@gmail.com> wrote:
>
>> for j in 1..len do
>>  mycommand += s[-1*j]
>>
>>
>
> very nice I like the use of your math. By multiplying the array index
> by negative one your sending the index a reverse number while your for
> loop traverses forward. This is perfect logic.
>
> Here is a rewrite with my while loop:
>
> s = "1234567890"
> r=String.new
> i = 1
> while i <= s.length
>  r << s[i*(-1)]
>  i+=1
> end
> printf s
> "0987654321"
>  => "0987654321"
>> y == x.reverse
> true
>

[toc] | [prev] | [next] | [standalone]


#3373

FromLarry Lv <larrylv1990@gmail.com>
Date2011-04-22 04:24 -0500
Message-ID<BANLkTikAR8_9CURSvyviSxTQyKZ8KTi68Q@mail.gmail.com>
In reply to#3371
[Note:  parts of this message were removed to make it a legal post.]

#!/usr/bin/env ruby

while line = gets.chomp
  r = String.new
  (1..line.length).each do |i|
    r << line[-1*i]
  end
  puts r
  puts r == line.reverse
end

On Fri, Apr 22, 2011 at 4:43 PM, Stu <stu@rubyprogrammer.net> wrote:

> One more with ruby blocks (This would be the ruby way =) )
>
> s = "1234567890"
> r = String.new
> s.length.times{|i| r << s[(i+1)*(-1)]}
>
> r == s.reverse
> true
>
> cheers!!!
>
> That was fun!!!... give me another =)
>
> ~Stu
> On Fri, Apr 22, 2011 at 3:32 AM, Stu <stu@rubyprogrammer.net> wrote:
> > On Fri, Apr 22, 2011 at 2:45 AM, Jose Calderon-Celis
> > <josecalderoncelis@gmail.com> wrote:
> >
> >> for j in 1..len do
> >>  mycommand += s[-1*j]
> >>
> >>
> >
> > very nice I like the use of your math. By multiplying the array index
> > by negative one your sending the index a reverse number while your for
> > loop traverses forward. This is perfect logic.
> >
> > Here is a rewrite with my while loop:
> >
> > s = "1234567890"
> > r=String.new
> > i = 1
> > while i <= s.length
> >  r << s[i*(-1)]
> >  i+=1
> > end
> > printf s
> > "0987654321"
> >  => "0987654321"
> >> y == x.reverse
> > true
> >
>
>


-- 
Best Regards,

*Larry Lv*
@ Baidu NLP

[toc] | [prev] | [next] | [standalone]


#3380

FromRubist Rohit <passionate_programmer@hotmail.com>
Date2011-04-22 06:56 -0500
Message-ID<9b44c5e6b085458e2f424484ddd83280@ruby-forum.com>
In reply to#3366
Thanks all for brilliant examples.

@Jose: Thanks so much. That was too close.

Jose Calderon-Celis wrote in post #994451:
> #!/usr/bin/env ruby
> #
> require 'rubygems'
>
> puts "ruby #{RUBY_VERSION}"
> s = "This is to test reverse of a string"
> p s
> len=s.length
> mycommand=""
> for j in 1..len do
>   mycommand += s[-1*j]
> end
> p mycommand
> Jose Calderon-Celis
> 5199906-7970
> http://www.tm.com.pe/mensajes/
>
>
>
> 2011/4/22 Rubist Rohit <passionate_programmer@hotmail.com>

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [prev] | [next] | [standalone]


#3369

FromStu <stu@rubyprogrammer.net>
Date2011-04-22 03:16 -0500
Message-ID<BANLkTik=tFCoKsaEgaUOYkFCtLXj7E=k7Q@mail.gmail.com>
In reply to#3356
Simple =)

s = "1234567890"
r=String.new
i = 1; while i <= s.length
  r << s[-i]
  i+=1
end

r == s.reverse
true

r is now the  reverse of s

On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit
<passionate_programmer@hotmail.com> wrote:
> I am trying this:
>
> mystring = gets
> mystring.scan(/..$/) {|x| puts x}
>
> It returns only the last character. Is it possible to add the above line
> in loop?
>
> --
> Posted via http://www.ruby-forum.com/.
>
>

[toc] | [prev] | [next] | [standalone]


#3374

FromRobert Dober <robert.dober@gmail.com>
Date2011-04-22 04:51 -0500
Message-ID<BANLkTimRen8f-FZeZ_LP3LebpGXVc7xRcA@mail.gmail.com>
In reply to#3356
What about

y = lambda{ | str | str.empty? ? "" : y[ str[1..-1] ] + str[0] }

Cheers
Robert


-- 
The 1,000,000th fibonacci number contains '42' 2039 times; that is
almost 30 occurrences more than expected (208988 digits).
N.B. The 42nd fibonacci number does not contain '1000000' that is
almost the expected 3.0e-06 times.

[toc] | [prev] | [next] | [standalone]


#3383

FromJose Calderon-Celis <josecalderoncelis@gmail.com>
Date2011-04-22 09:42 -0500
Message-ID<BANLkTi=OPJsfHbS1xG1KQ+1EeJLAHYck-w@mail.gmail.com>
In reply to#3374
[Note:  parts of this message were removed to make it a legal post.]

@Robert: Thanks, Cheers

#!/usr/bin/env ruby
#
require 'rubygems'

y = lambda{ | str |
# puts "  #{str}"
  str.empty? ? "" : y[ str[1..-1] ] + str[0]
}

s="1234567890"
p s
p y.call(s)

output:./reverseL.rb
"1234567890"
"0987654321"


---
Jose Calderon-Celis





2011/4/22 Robert Dober <robert.dober@gmail.com>

> What about
>
> y = lambda{ | str | str.empty? ? "" : y[ str[1..-1] ] + str[0] }
>
> Cheers
> Robert
>
>
>
>

[toc] | [prev] | [next] | [standalone]


#3395

FromBrian Candler <b.candler@pobox.com>
Date2011-04-23 06:11 -0500
Message-ID<397074d5c207a12feaa27f2d0a27a9e8@ruby-forum.com>
In reply to#3383
I'm surprised nobody has yet shown using 'inject', as for once it makes 
sense here.

a = "foobar"
puts a.each_char.inject("") { |str,chr| chr+str }   # raboof

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [prev] | [next] | [standalone]


#3400

FromRobert Dober <robert.dober@gmail.com>
Date2011-04-23 07:34 -0500
Message-ID<BANLkTimR+QL9ofXjXaojQa4E0TbDqkXkuA@mail.gmail.com>
In reply to#3395
On Sat, Apr 23, 2011 at 1:11 PM, Brian Candler <b.candler@pobox.com> wrote:
> I'm surprised nobody has yet shown using 'inject', as for once it makes
that was mean ;)



-- 
The 1,000,000th fibonacci number contains '42' 2039 times; that is
almost 30 occurrences more than expected (208988 digits).
N.B. The 42nd fibonacci number does not contain '1000000' that is
almost the expected 3.0e-06 times.

[toc] | [prev] | [next] | [standalone]


#3376

FromHans Mackowiak <hanmac@gmx.de>
Date2011-04-22 05:33 -0500
Message-ID<b7ddac405053498cd98b0535d54ff718@ruby-forum.com>
In reply to#3356
why without reverse functions?
like:
"abc".each_char.reverse_each {|c| p c}

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [prev] | [next] | [standalone]


#3379

FromHarry Kakueki <list.push@gmail.com>
Date2011-04-22 06:15 -0500
Message-ID<BANLkTik3p01jky5QD6cozw_fUE68__tcqQ@mail.gmail.com>
In reply to#3356
On Fri, Apr 22, 2011 at 12:54 PM, Rubist Rohit
<passionate_programmer@hotmail.com> wrote:
> I am trying this:
>
> mystring = gets
> mystring.scan(/..$/) {|x| puts x}
>
> It returns only the last character. Is it possible to add the above line
> in loop?
>
> --


s = "I am a string."

t = ""
s.each_char{|f| t.insert(0,f)}
p t     #> ".gnirts a ma I"




Harry

[toc] | [prev] | [next] | [standalone]


#3381

Fromspiralofhope <spiralofhope_rubyml@lavabit.com>
Date2011-04-22 07:05 -0500
Message-ID<20110422050430.3ee575f0@user-GA-MA785GM-US2H>
In reply to#3379
On Fri, 22 Apr 2011 20:15:34 +0900
Harry Kakueki <list.push@gmail.com> wrote:

> s = "I am a string."
> 
> t = ""
> s.each_char{|f| t.insert(0,f)}
> p t     #> ".gnirts a ma I"

Oh, of course!  This makes a lot of sense to me..

Some other examples using .length were also very easy on my brain.  =)


-- 
http://spiralofhope.com

[toc] | [prev] | [next] | [standalone]


#3382

FromRubist Rohit <passionate_programmer@hotmail.com>
Date2011-04-22 07:17 -0500
Message-ID<606f66def949fec7109c6404d8b75354@ruby-forum.com>
In reply to#3379
@Harry,

That was excellent. Very little code and fits to my condition of not 
using arrays as well.

Harry Kakueki wrote in post #994483:
> On Fri, Apr 22, 2011 at 12:54 PM, Rubist Rohit
>
> s = "I am a string."
>
> t = ""
> s.each_char{|f| t.insert(0,f)}
> p t     #> ".gnirts a ma I"


> Harry

-- 
Posted via http://www.ruby-forum.com/.

[toc] | [prev] | [next] | [standalone]


#3413

FromJosh Cheek <josh.cheek@gmail.com>
Date2011-04-23 13:33 -0500
Message-ID<BANLkTikE5euDUT+ZW+pd1KJFPdNkVMUW0w@mail.gmail.com>
In reply to#3356
[Note:  parts of this message were removed to make it a legal post.]

On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit <
passionate_programmer@hotmail.com> wrote:

> I am trying this:
>
> mystring = gets
> mystring.scan(/..$/) {|x| puts x}
>
> It returns only the last character. Is it possible to add the above line
> in loop?
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
Thought I'd join the fun :)


s = "12345"

# using reverse
s.reverse # => "54321"


# using each_char
s2 = ""
s.each_char { |char| s2 = char << s2 }
s2 # => "54321"


# using scan
s2 = ""
s.scan(/./) { |char| s2 = char << s2 }
s2 # => "54321"


# using unix (this doesn't escape all chars properly, though)
`rev <<<#{s.inspect}`.chomp # => "54321"


# using recursion
rev = lambda do |string|
  if string.empty?
    ""
  else
    rev.call(string[1..-1]) << string[0,1]
  end
end
rev.call s # => "54321"


# exchanging chars
s2 = s.dup
s2.length./(2).times { |i| s2[i] , s2[-i-1] = s2[-i-1] , s2[i] }
s2 # => "54321"

[toc] | [prev] | [next] | [standalone]


#3414

FromDuke Normandin <dukeofperl@ml1.net>
Date2011-04-23 13:56 -0500
Message-ID<alpine.DEB.2.00.1104231247300.9169@fryrpg-zna>
In reply to#3413
On Sun, 24 Apr 2011, Josh Cheek wrote:

> On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit <
> passionate_programmer@hotmail.com> wrote:
>
> > I am trying this:
> >
> > mystring = gets
> > mystring.scan(/..$/) {|x| puts x}
> >
> > It returns only the last character. Is it possible to add the above line
> > in loop?
> >
> > --
> > Posted via http://www.ruby-forum.com/.
> >
> >
> Thought I'd join the fun :)

[snip the good stuff]

Now that's what I call a _constructive- reply! All good stuff for
Ruby noobs! While some others here are going into my 'killfile', you
are a rising *star*. :))

It's like a long-time friend of mine used to say - may she rest in
peace! - opinions and advice are like assholes! Everybody's got one!
It's the _informed_  opinions and advice that I'm after - and you seem
to have it! All the other bullshit is going into my bit-bucket - not
now! but right now! :D

Much obliged!
-- 
Duke

[toc] | [prev] | [next] | [standalone]


#3416

FromAdam Prescott <adam@aprescott.com>
Date2011-04-23 16:16 -0500
Message-ID<BANLkTikb7TrSZo3F25ULpqXN5vX8ymgqEQ@mail.gmail.com>
In reply to#3413
On Sat, Apr 23, 2011 at 7:33 PM, Josh Cheek <josh.cheek@gmail.com> wrote:
> # using reverse
> # using each_char
> # using scan
> # using unix (this doesn't escape all chars properly, though)
> # using recursion
> # exchanging chars

I feel a benchmark coming, of all the suggestions so far. :)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.ruby


csiph-web