Answers for "Replacing consecutive numbers with dash between first and last in a range"

0

Replacing consecutive numbers with dash between first and last in a range

// Replacing consecutive numbers with dash between first and last in a range

fn convert_to_range(first: i32, last: i32) -> String {
    if last - first >= 2 {
        first.to_string() + "-" + &last.to_string()
    } else if first != last {
        first.to_string() + "," + &last.to_string()
    } else {
        first.to_string()
    }
}    

fn range_extraction(a: &[i32]) -> String {
    let mut r: Vec<i32> = Vec::new();
    let mut finals: Vec<String> = Vec::new();
    for &x in a.iter() {
        match r.last() {
            Some(y) => {
                if x - y == 1 {
                    r.push(x);
                } else {
                    finals.push(convert_to_range(*r.first().unwrap(), *r.last().unwrap()));
                    r = vec![x];
                }
            },
            None => {
                r.push(x);
            },
        }
    }
    finals.push(convert_to_range(*r.first().unwrap(), *r.last().unwrap())); 
    finals.join(",")
}

fn main() {
    // answer: "-3--1,2,10,15,16,18-20"
    println!("{} ", range_extraction(&[-3,-2,-1,2,10,15,16,18,19,20]));
}
Posted by: Guest on September-07-2021
0

Replacing consecutive numbers with dash between first and last in a range

# Replacing consecutive numbers with dash between first and last in a range

def range_extraction(args):
    out = []
    beg = end = args[0]
    
    for n in args[1:] + [""]:        
        if n != end + 1:
            if end == beg:
                out.append( str(beg) )
            elif end == beg + 1:
                out.extend( [str(beg), str(end)] )
            else:
                out.append( str(beg) + "-" + str(end) )
            beg = n
        end = n
    
    return ",".join(out)

print (range_extraction([-3,-2,-1,2,10,15,16,18,19,20]));   #, '-3--1,2,10,15,16,18-20')
Posted by: Guest on September-07-2021
0

Replacing consecutive numbers with dash between first and last in a range

# Replacing consecutive numbers with dash between first and last in a range
def range_extraction(list)
  list.chunk_while {|i, j| i+1 == j }.map do |a|
    if a.size > 2
      a.first.to_s + "-" + a.last.to_s
    else
      a  
    end
  end.join(',')
end

print range_extraction([-3,-2,-1,2,10,15,16,18,19,20])  # "-3--1,2,10,15,16,18-20"
Posted by: Guest on September-07-2021

Code answers related to "Replacing consecutive numbers with dash between first and last in a range"

Browse Popular Code Answers by Language