RosettaCodeData/Task/Range-extraction/Objeck/range-extraction.objeck
2023-07-01 13:44:08 -04:00

46 lines
1.3 KiB
Text

class IdentityMatrix {
function : Main(args : String[]) ~ Nil {
Compress2Range("-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20")->PrintLine();
Compress2Range("0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39")->PrintLine();
}
function : Compress2Range(expanded : String) ~ String {
result := "";
nums := expanded->ReplaceAll(" ", "")->Split(",");
firstNum := nums[0]->ToInt();
rangeSize := 0;
for(i:= 1; i < nums->Size(); i += 1;) {
thisNum := nums[i]->ToInt();
if(thisNum - firstNum - rangeSize = 1) {
rangeSize += 1;
}
else{
if(rangeSize <> 0){
result->Append(firstNum);
result->Append((rangeSize = 1) ? ",": "-");
result->Append(firstNum+rangeSize);
result->Append(",");
rangeSize := 0;
}
else {
result->Append(firstNum);
result->Append(",");
};
firstNum := thisNum;
};
};
if(rangeSize <> 0){
result->Append(firstNum);
result->Append((rangeSize = 1) ? "," : "-");
result->Append(firstNum + rangeSize);
rangeSize := 0;
}
else {
result->Append(firstNum);
};
return result;
}
}