Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I divided the whole string into to 3-character parts. Then I checked for each triplet if first character is equal to S
, second to O
and third to S
. And counted the changed letters.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.*; public class MarsExploration { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); String msg = stdin.nextLine(); int result = 0; for(int i = 0; i < msg.length(); i += 3) { if(msg.charAt(i) != 'S') { result++; } if(msg.charAt(i + 1) != 'O') { result++; } if(msg.charAt(i + 2) != 'S') { result++; } } System.out.println(result); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
'use strict'; const processData = input => { const msg = input; let result = 0; for(let i = 0; i < msg.length; i += 3) { if(msg.charAt(i) != 'S') { result++; } if(msg.charAt(i + 1) != 'O') { result++; } if(msg.charAt(i + 2) != 'S') { result++; } } console.log(result); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 |
object MarsExploration extends App { val line = Source.stdin.getLines().toList.head val tris = line.grouped(3) val sosDiffs = tris.map(diffSignal) println(sosDiffs.sum) def diffSignal(s: String): Long = { (if(s(0) == 'S') 0 else 1) + (if(s(1) == 'O') 0 else 1) + (if(s(2) == 'S') 0 else 1) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
msg = gets.to_s.strip index = 0 result = 0 while index < msg.length do result += 1 if msg[index] != 'S' result += 1 if msg[index + 1] != 'O' result += 1 if msg[index + 2] != 'S' index += 3 end puts result |
This program will not work if input has one less char for e.e SOSSO or SO…
correct program will be:-
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String S = in.next();
//int i=0;
int count=0;
int len=S.length();
for(int i=0;i<len-1;i=i+3)
{
if(S.charAt(i)!='S' || ((int)S.charAt(i)==0))
{
count++;
}
if(S.charAt(i+1)!='O'|| ((int)S.charAt(i+1)==0))
{
count++;
}
if(S.charAt(i+2)!='S' || ((int)S.charAt(i+2)==0 ))
{
count++;
}
}
System.out.println(count);
}
}
You do not need to check that. Statement constraints are following
1 <= |S| <= 99
The input string will never "has one less char"