Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to rearrange an array into a zig-zag pattern (a < b > c < d > e < f > g) in Ruby

1 Answer

0 votes
# This program rearranges an array into a zig-zag pattern, where the elements 
# alternate between being smaller and larger than their neighbors

def rearrange_into_zigzag(arr)
  (0...arr.length - 1).each do |i|
    if i.even?
      # Expect arr[i] < arr[i + 1]
      if arr[i] > arr[i + 1]
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
      end
    else
      # Expect arr[i] > arr[i + 1]
      if arr[i] < arr[i + 1]
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
      end
    end
  end

  arr
end

arr = [3, 5, 1, 7, 9, 6, 4, 2]

rearrange_into_zigzag(arr)

p arr


# run:
#
# [3, 5, 1, 9, 6, 7, 2, 4]
#

 



answered Oct 8 by avibootz

Related questions

...